小结
这两天过一下springboot中的一些东西,居然看到有结合队列的内容,顺便拿来学一下。但是感觉自己学+做之后,掌握还是不太到位,具体是哪里不到位,是流程吗,还是操作细节。MQ就是消息缓存中间件,为了避免同步执行导致浪费之间,很多时候只需要把主流程执行完,这个任务就算完成,类似于下单结算和下单之后的短信通知,两个业务可以分开,降低了服务器压力,松耦合。同时也提高了系统的处理能力。
代码01
消息发送实现类
@Service
public class MessageServiceActiveImpl implements MessageService {
@Autowired
private JmsMessagingTemplate messagingTemplate;
@Override
public void sendMessage(String id) {
System.out.println("待发送短信的订单已纳入队列:id:"+id);
messagingTemplate.convertAndSend("order.queue.id",id);
}
@Override
public String doMessage() {
String id = messagingTemplate.receiveAndConvert("order.queue.id",String.class);
System.out.println("已完成短信发送业务。id:" + id);
return id;
}
}
监听器
@Component
public class MessagerListener {
@JmsListener(destination = "order.queue.id")
@SendTo("order.other.queue.demo")
public String receive(String id){
System.out.println("已完成短信发送业务,id"+id);
return "new"+id;
}
}
依赖pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
<version>2.5.4</version>
</dependency>
配置文件yaml
server:
port: 9300
spring:
activemq:
broker-url: tcp://localhost:61616
jms:
template:
default-destination: itheima
pub-sub-domain: true
此外就是通过两个控制器的接口,利用postman发送请求,进行调用。
这两天另外找时间去优化下自己以前写的代码,试试java8stream流写法。
整理清除业务逻辑,降低后期运维成本。
爱自己,come on!
git地址
git@gitee.com:shenjhhh/black-horse-spring-boot2-black.git