SpringCloud基础框架搭建 –6 drools

这是系列搭建springcloud基础框架的文章,内容包括集成shiro、Mysql主从、seata、activiti、drools、hadoop大数据常用组件、keepalive+nginx https配置等;

创建 chen-drools: 部分参考 chen-manage

<!--drools规则引擎-->
<dependency>
    <groupId>org.drools</groupId>
    <artifactId>drools-core</artifactId>
    <version>7.10.0.Final</version>
</dependency>
<dependency>
    <groupId>org.drools</groupId>
    <artifactId>drools-compiler</artifactId>
    <version>7.10.0.Final</version>
</dependency>
<dependency>
    <groupId>org.kie</groupId>
    <artifactId>kie-api</artifactId>
    <version>7.10.0.Final</version>
</dependency>
<dependency>
    <groupId>org.kie</groupId>
    <artifactId>kie-spring</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </exclusion>
    </exclusions>
    <version>7.10.0.Final</version>
</dependency>

入口Application

@SpringBootApplication(exclude = {DruidDataSourceAutoConfigure.class})
@EnableFeignClients(value = {"com.chen.frame.api"})
@ComponentScan(basePackages = {"com.chen.frame.common", "com.chen.frame.api", "com.chen.frame.drools"})
public class DroolsApplication {

    public static void main(String ...args) {
        //SpringApplication.run(ManagerApplication.class, args);

        new SpringApplicationBuilder(DroolsApplication.class)
                .properties(new ConcurrentHashMap<String, Object>(){{
                    put("frame.module.basePackages", "com.chen.frame.drools.mapper");
                }}).run(args);
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer () {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        configurer.setIgnoreUnresolvablePlaceholders(true);
        return configurer;
    }

    @Bean
    @Primary
    public ObjectMapper xssObjectMapper(Jackson2ObjectMapperBuilder builder) {
        // 解析器
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        // 注册XSS SQL 解析器
        SimpleModule xssModule = new SimpleModule("XssStringJsonSerializer");
        xssModule.addSerializer(new XssSqlStringJsonSerializer());
        objectMapper.registerModule(xssModule);
        return objectMapper;
    }
}

bootstrap.yml

server:
  port: 8066

spring:
  application:
    name: chen-drools
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
      config:
        server-addr: localhost:8848
        file-extension: yml
        group: DEFAULT_GROUP
        shared-configs[0]:
          data-id: application-dev.yml
          group: DEFAULT_GROUP
          refresh: true
        shared-configs[1]:
          data-id: chen-druid-dev.yml
          group: DEFAULT_GROUP
          refresh: true
  profiles:
    active: dev

  main:
    allow-bean-definition-overriding: true

  redis:
    host: 127.0.0.1
    port: 6379
    password: 123456
    timeout: 3000
    max-wait: 30000
    max-active: 100
    max-idle: 20
    min-idle: 0

mybatis:
  mapperLocations: classpath:mapper/**Mapper.xml
  type-aliases-package: com.chen.frame.drools.mapper
  configuration:
    map-underscore-to-camel-case: true

# shardingsphere 数据库安全检测
management:
  health:
    db:
      enabled: false

DroolsConfig.java

package com.chen.frame.drools.configuration;

import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.kie.spring.KModuleBeanFactoryPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.Resource;
import java.io.IOException;
/**
 * 规则引擎配置类
 */
@Configuration
public class DroolsConfig {
    //指定规则文件存放的目录
    private static final String RULES_PATH = "rules/";
    private final KieServices kieServices = KieServices.Factory.get();
    @Bean
    @ConditionalOnMissingBean
    public KieFileSystem kieFileSystem() throws IOException {
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        ResourcePatternResolver resourcePatternResolver =
                new PathMatchingResourcePatternResolver();
        Resource[] files =
                resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "*.*");
        String path = null;
        for (Resource file : files) {
            path = RULES_PATH + file.getFilename();
            kieFileSystem.write(ResourceFactory.newClassPathResource(path, "UTF-8"));
        }
        return kieFileSystem;
    }
    @Bean
    @ConditionalOnMissingBean
    public KieContainer kieContainer() throws IOException {
        KieRepository kieRepository = kieServices.getRepository();
        kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
        KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem());
        kieBuilder.buildAll();
        return kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
    }
    @Bean
    @ConditionalOnMissingBean
    public KieBase kieBase() throws IOException {
        return kieContainer().getKieBase();
    }
    @Bean
    @ConditionalOnMissingBean
    public KModuleBeanFactoryPostProcessor kiePostProcessor() {
        return new KModuleBeanFactoryPostProcessor();
    }
}

/resources创建 rules目录,添加 hello.drl

//图书优惠规则
package com.chen.frame.drools
import com.chen.frame.api.frame.bean.vo.OrderVO

//规则一:所购图书总价在100元以下的没有优惠
rule "book_discount_1"
    when
        $order:OrderVO(originalPrice < 100)
    then
        $order.setRealPrice($order.getOriginalPrice());
        System.out.println("成功匹配到规则一:所购图书总价在100元以下的没有优惠");
end

//规则二:所购图书总价在100到200元的优惠20元
rule "book_discount_2"
    when
        $order:OrderVO(originalPrice < 200 && originalPrice >= 100)
    then
        $order.setRealPrice($order.getOriginalPrice() - 20);
        System.out.println("成功匹配到规则二:所购图书总价在100到200元的优惠20元");
end

//规则三:所购图书总价在200到300元的优惠50元
rule "book_discount_3"
    when
        $order:OrderVO(originalPrice <= 300 && originalPrice >= 200)
    then
        $order.setRealPrice($order.getOriginalPrice() - 50);
        System.out.println("成功匹配到规则三:所购图书总价在200到300元的优惠50元");
end

//规则四:所购图书总价在300元以上的优惠100元

rule "book_discount_4"
    when
        $order:OrderVO(originalPrice >= 300)
    then
        $order.setRealPrice($order.getOriginalPrice() - 100);
        System.out.println("成功匹配到规则四:所购图书总价在300元以上的优惠100元");
end

在chen-frame-api bean/vo 下创建上 OrderVO 类:

@Data
public class OrderVO {
    private Double originalPrice;//订单原始价格,即优惠前价格
    private Double realPrice;//订单真实价格,即优惠后价格
}

创建接口及实现类:

public interface DroolsService {

    public void testDrools();
}
///////////////////////////
@Service
public class DroolsServiceImpl implements DroolsService {

    @Autowired
    private KieBase kieBase;

    @Override
    public void testDrools() {
        KieSession kieSession = kieBase.newKieSession();

        //构造订单对象,设置原始价格,由规则引擎根据优惠规则计算优惠后的价格
        OrderVO order = new OrderVO();
        order.setOriginalPrice(210D);

        //将数据提供给规则引擎,规则引擎会根据提供的数据进行规则匹配
        kieSession.insert(order);

        //激活规则引擎,如果规则匹配成功则执行规则
        kieSession.fireAllRules();
        //关闭会话
        kieSession.dispose();

        System.out.println("优惠前原始价格:" + order.getOriginalPrice() +
                ",优惠后价格:" + order.getRealPrice());
    }
}

创建 droolscontroller

@RestController
@RequestMapping(value = "/drools")
public class DroolsController {

    @Autowired
    private DroolsService droolsService;

    @GetMapping(value = "/testDrools")
    public ResultData testDrools() {
        droolsService.testDrools();

        return new ResultData(ResultStatus.SUCCESS, "ok");
    }
}
欢迎您的到来,感谢您的支持!

为您推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注