RabbitConfiguration.java
2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.diligrp.assistant.sms;
import com.diligrp.assistant.shared.domain.AsyncMessage;
import com.diligrp.assistant.sms.service.SmsScheduleService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class RabbitConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(RabbitConfiguration.class);
@Resource
private SmsScheduleService smsScheduleService;
/**
* 短信服务MQ延时队列
* 队列为持久化、非独占式且不自动删除的队列, 利用RabbitMQ延时插件实现延时功能https://github.com/rabbitmq/rabbitmq-delayed-message-exchange
*/
@Bean
public Queue smsDelayQueue() {
return new Queue(Constants.SMS_DELAY_QUEUE, true, false, false);
}
/**
* 短信服务MQ延时交换机
*/
@Bean
public CustomExchange smsDelayExchange() {
Map<String, Object> arguments = new HashMap<>();
arguments.put("x-delayed-type", "direct");
return new CustomExchange(Constants.SMS_DELAY_EXCHANGE, "x-delayed-message", true, false, arguments);
}
/**
* 短信服务MQ延时队列和交换机的绑定
*/
@Bean
public Binding smsDelayBinding() {
return BindingBuilder.bind(smsDelayQueue()).to(smsDelayExchange()).with(Constants.SMS_DELAY_KEY).noargs();
}
@RabbitHandler
@RabbitListener(queues = {Constants.SMS_DELAY_QUEUE})
public void onMessage(Message message) {
byte[] packet = message.getBody();
MessageProperties properties = message.getMessageProperties();
String charSet = properties != null && properties.getContentEncoding() != null
? properties.getContentEncoding() : StandardCharsets.UTF_8.name();
try {
String body = new String(packet, charSet);
LOGGER.info("Handling sms service job: {}", body);
AsyncMessage job = AsyncMessage.from(body);
if (job.getType() == Constants.MESSAGE_TEMPLATE_STATE) {
smsScheduleService.executeSmsTemplateJob(job.getPayload());
} else {
LOGGER.error("Unrecognized sms service job: {}", job.getType());
}
} catch (Exception ex) {
LOGGER.error("Handle sms service job exception", ex);
}
}
}