0


项目中使用Cron与RabbitMQ实现定时任务

实现思路:在定时任务中引入rabbitmq的模块,rabbitmq模块添加对应的消息监听,在定时任务模块使用cron的方式配置定时任务。

新建模块service_task,添加依赖,引入之前创建的mq工具类模块

<dependencies>
        <dependency>
            <groupId>com.lzq</groupId>
            <artifactId>rabbit_util</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
 </dependencies>

配置文件

# 服务端口
server.port=8208
# 服务名
spring.application.name=service-task
# 环境设置:dev、test、prod
spring.profiles.active=dev
# nacos服务地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8888
#rabbitmq地址
spring.rabbitmq.host=192.168.8.139
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

创建启动类

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableDiscoveryClient
public class ServiceTaskApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceTaskApplication.class, args);
    }
}

在rabbit-util模块MqConst类添加

//定时任务
public static final String EXCHANGE_DIRECT_TASK = "exchange.direct.task";
public static final String ROUTING_TASK_8 = "task.8";
//队列
public static final String QUEUE_TASK_8 = "queue.task.8";

Task模块对应类

@Component
@EnableScheduling
public class ScheduledTask {
    @Autowired
    private RabbitService rabbitService;
    /**
     * cron表达式设置规则
     * 每天8点执行 提醒就诊
     */
    @Scheduled(cron = "0 0 8 * * ?")  //每天8点
//    @Scheduled(cron = "0/10 * * * * ?")
    public void task1() {
        System.out.println(new Date().toLocaleString());
        //发送短信
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_TASK, MqConst.ROUTING_TASK_8,"");
    }
}

添加mq监听

@Component
public class OrderReceiver {
    @Autowired
    private OrderInfoService orderService;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TASK_8, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_TASK),
            key = {MqConst.ROUTING_TASK_8}
    ))
    public void patientTips(Message message, Channel channel) throws IOException {
        orderService.patientTips();
    }
}

OrderService接口和实现

 @Override
    public void patientTips() {
        //查询当天就诊人手机号
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reserve_date", new DateTime().toString("yyyy-MM-dd"));
        //未取消预约的订单
        queryWrapper.ne("order_status",-1);
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
        for (OrderInfo orderInfo : orderInfoList) {
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_TASK, MqConst.ROUTING_TASK_8,msmVo);
        }
    }
标签: rabbitmq 分布式 java

本文转载自: https://blog.csdn.net/weixin_52210557/article/details/122764304
版权归原作者 远走于梦游 所有, 如有侵权,请联系我们删除。

“项目中使用Cron与RabbitMQ实现定时任务”的评论:

还没有评论