springboot整合rabbitmq發(fā)送消息
構(gòu)建項目
- 構(gòu)建gradle
repositories {
mavenCentral()
}
ext{
springBootVersion = "2.0.3.RELEASE"
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-amqp:1.5.2.RELEASE")
compile("org.springframework.boot:spring-boot-starter-web:$springBootVersion")
compile("org.springframework.boot:spring-boot-starter-undertow:$springBootVersion")
}
//排除tomcat
configurations {
compile.exclude module: 'spring-boot-starter-tomcat'
}
-
手動創(chuàng)建queues
生產(chǎn)者
@Component
public class DemoProducer {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String sendMsg = "msg " + new Date();
System.out.println("生產(chǎn)者開始生產(chǎn)信息 : " + sendMsg);
this.rabbitTemplate.convertAndSend("msg", sendMsg);
}
}
- 消費者
@Component
@RabbitListener(queues = "msg")
public class DemoReceiver {
@RabbitHandler
public void process(String msg) {
System.out.println("消費者 收到信息 : " + msg);
}
}
- 測試controller
@Controller
@RequestMapping("/rabbit")
public class DemoController {
@Autowired
private DemoProducer demoProducer;
@RequestMapping("/hello")
@ResponseBody
public String hello(HttpServletRequest request) {
demoProducer.send();
return "success";
}
}
- yml配置
spring:
rabbitmq:
host: ######
port: ######
username: ######
password: ######
virtual-host: /
server:
port: 9000