点击上方“程序员蜗牛g”,选择“设为星标”
跟蜗牛哥一起,每天进步一点点
程序员蜗牛g
大厂程序员一枚 跟蜗牛一起 每天进步一点点
31篇原创内容
公众号
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/coupon_system?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# MyBatis 配置
mybatis.type-aliases-package=com.example.couponsystemdb.model
mybatis.mapper-locations=classpath*:mapper/*.xml
ShoppingCart.java
package com.example.couponsystemdb.model;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
publicclass ShoppingCart {
privatedouble totalPrice = 0; // 购物车总价格
privatefinal List<Item> items = new ArrayList<>(); // 商品列表
/**
* 向购物车添加商品
* @param item 商品对象
*/
public void addItem(Item item) {
items.add(item);
totalPrice += item.getPrice();
}
/**
* 应用折扣
* @param discount 折扣比例(例如 0.10 表示 10% 折扣)
*/
public void applyDiscount(double discount) {
totalPrice -= totalPrice * discount;
}
}
Item.java
package com.example.couponsystemdb.model;
import lombok.Data;
@Data
publicclass Item {
private String name; // 商品名称
private String category; // 商品类别
privatedouble price; // 商品价格
/**
* 构造函数
* @param name 商品名称
* @param category 商品类别
* @param price 商品价格
*/
public Item(String name, String category, double price) {
this.name = name;
this.category = category;
this.price = price;
}
}
CouponRule.java
package com.example.couponsystemdb.model;
import lombok.Data;
@Data
public class CouponRule {
private Long id; // 规则ID
private String ruleName; // 规则名称
private String description; // 规则描述
private String conditionExpression; // 条件表达式
private String actionExpression; // 动作表达式
}
SQL 脚本
CREATE DATABASE coupon_system;
USE coupon_system;
CREATE TABLE coupon_rule (
idBIGINT AUTO_INCREMENT PRIMARY KEY,
rule_name VARCHAR(255) NOT NULL,
description TEXT,
condition_expression TEXTNOT NULL,
action_expression TEXTNOT NULL
);
INSERT INTO coupon_rule (rule_name, description, condition_expression, action_expression) VALUES
('Total Price Discount Rule', 'Offers a 10% discount if the total price exceeds 1000',
'cart.getTotalPrice() > 1000',
'cart.applyDiscount(0.10); System.out.println("Applied 10% discount for total price exceeding 1000");'),
('Category Discount Rule', 'Offers an additional 5% discount on Electronics category',
'cart.getItems().stream().anyMatch(item -> item.getCategory().equals("Electronics"))',
'cart.applyDiscount(0.05); System.out.println("Applied 5% discount for purchasing electronics");');
DynamicCouponRule.java
package com.example.couponsystemdb.rule;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Fact;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.core.DynamicRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
publicclass DynamicCouponRule extends DynamicRule {
@Autowired
private CouponService couponService;
/**
* 评估条件
* @param facts 事实对象
* @return 是否满足条件
* @throws Exception 异常
*/
@Override
@Condition
public boolean evaluate(Facts facts) throws Exception {
returnsuper.evaluate(facts);
}
/**
* 执行动作
* @param facts 事实对象
* @throws Exception 异常
*/
@Override
@Action
public void execute(Facts facts) throws Exception {
super.execute(facts);
}
/**
* 从数据库设置规则
* @param ruleId 规则ID
*/
public void setRuleFromDatabase(Long ruleId) {
CouponRule couponRule = couponService.getCouponRuleById(ruleId);
setName(couponRule.getRuleName());
setDescription(couponRule.getDescription());
setConditionExpression(couponRule.getConditionExpression());
setActionExpression(couponRule.getActionExpression());
}
}
EasyRulesConfig.java
package com.example.couponsystemdb.config;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
publicclass EasyRulesConfig {
/**
* 配置规则引擎
* @return 规则引擎实例
*/
@Bean
public RulesEngine rulesEngine() {
returnnew DefaultRulesEngine();
}
}
CouponService.java
package com.example.couponsystemdb.service;
import com.example.couponsystemdb.mapper.CouponRuleMapper;
import com.example.couponsystemdb.model.CouponRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
publicclass CouponService {
@Autowired
private CouponRuleMapper couponRuleMapper;
/**
* 根据规则ID获取规则
* @param id 规则ID
* @return 规则对象
*/
public CouponRule getCouponRuleById(Long id) {
return couponRuleMapper.selectById(id);
}
}
8. 创建 Mapper 接口
CouponRuleMapper.java
package com.example.couponsystemdb.mapper;
import com.example.couponsystemdb.model.CouponRule;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface CouponRuleMapper {
/**
* 根据规则ID查询规则
* @param id 规则ID
* @return 规则对象
*/
@Select("SELECT * FROM coupon_rule WHERE id = #{id}")
CouponRule selectById(Long id);
}
9. 编写主应用程序类
CouponSystemApplication.java
package com.example.couponsystemdb;
import com.example.couponsystemdb.model.ShoppingCart;
import com.example.couponsystemdb.model.Item;
import com.example.couponsystemdb.rule.DynamicCouponRule;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
publicclass CouponSystemApplication implements CommandLineRunner {
@Autowired
private RulesEngine rulesEngine; // 规则引擎
@Autowired
private DynamicCouponRule dynamicCouponRule; // 动态规则
@Autowired
private CouponService couponService; // 优惠券服务
public static void main(String[] args) {
SpringApplication.run(CouponSystemApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
ShoppingCart cart = new ShoppingCart(); // 创建购物车
cart.addItem(new Item("Laptop", "Electronics", 1200)); // 添加商品
cart.addItem(new Item("Book", "Books", 30)); // 添加商品
Facts facts = new Facts(); // 创建事实对象
facts.put("cart", cart); // 将购物车放入事实对象
Rules rules = new Rules(); // 创建规则集合
// 从数据库加载规则并注册到规则引擎
Long[] ruleIds = {1L, 2L}; // 数据库中的规则ID
for (Long ruleId : ruleIds) {
dynamicCouponRule.setRuleFromDatabase(ruleId); // 从数据库设置规则
rules.register(dynamicCouponRule); // 注册规则
}
rulesEngine.fire(rules, facts); // 执行规则引擎
System.out.println("Final price after discounts: " + cart.getTotalPrice()); // 输出最终价格
}
}
最后说一句(求关注!别白嫖!)
如果这篇文章对您有所帮助,或者有所启发的话,求一键三连:点赞、转发、在看。
关注公众号:woniuxgg,在公众号中回复:笔记 就可以获得蜗牛为你精心准备的java实战语雀笔记,回复面试、开发手册、有超赞的粉丝福利!