【综合学习】springboot项目使用rabbitmq (简单粗暴) 2020年1月19日
程序员文章站
2022-06-08 18:39:17
...
1.项目依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
<version>LATEST</version>
</dependency>
2. 配置文件
#后面三个参数主要是用于“并发量的配置”,表示:并发消费者的初始化值,并发消费者的最大值,每个消费者每次监听时可拉取处理的消息数量。
spring.rabbitmq.host=192.168.101.103
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=123456
spring.rabbitmq.listener.concurrency=10
spring.rabbitmq.listener.max-concurrency=20
spring.rabbitmq.listener.prefetch=5
3. 注解,新建channel
DirectConfig.java
package starter.rabbitmq;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author zs
*/
@Configuration
public class DirectConfig {
@Bean
public Queue notifyTestQueue() {
return new Queue("notify.test");
}
}
4. 生产者
NotifyTestSender.java
package starter.rabbitmq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 添加一个消息发送类(生产者)
* @author zs
*/
@Slf4j
@Component
public class NotifyTestSender{
@Autowired
private AmqpTemplate rabbitTemplate;
public void sender(String msg){
log.info("notify.payment send message: "+msg);
rabbitTemplate.convertAndSend("notify.test", msg);
}
}
5.消费者
NotifyTestReceive.java
package starter.rabbitmq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* @author zs
*/
@Slf4j
@Component
@RabbitListener(queues = "notify.test")
public class NotifyTestReceive{
@RabbitHandler
public void receive(String msg) {
log.info("notify.test receive message: "+msg);
}
}
6.随便搞个控制器测试下
RabbitImpl.java
package starter.api.impl;
import api.dto.MqSendDTO;
import api.interfaces.IRabbit;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import starter.rabbitmq.PaymentNotifySender;
/**
* @author zs
*/
@Api(value = "/rabbit",tags = "rabbit控制器")
@RestController
public class RabbitImpl implements IRabbit {
@Autowired
private NotifyTestSendersender;
@ApiOperation(value = "sendMqTest")
@GetMapping("/sendMqTest")
@Override
public String sendMqTest(MqSendDTO mqSendDTO) {
sender.sender("test send:" + JSONObject.toJSONString(mqSendDTO));
return "";
}
}
7.上个成功的图。
经测试发现,如果注释掉消费者部分,即消息不会被消费掉,则rabbitmq的web页面可以看到消息内容。