Springboot+rabbitmq,已有一个域名指向端口5672了,所以只需要配置host,不需要配置port,但是系统会默认配置端口5672,如何取消这个默认端口。
你的rabbitmq端口是多少
修改rabbitmq的端口
不配置端口的话还是会使用默认端口5672,报如下错误
以上就是RabbitMQ的基本用法,接下来还是要整合到SpringBoot中使用。
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
配置
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.publisher-confirms=true
spring.rabbitmq.virtual-host=/
RabbitMQ模式有很多,还是演示一下最简单的模式,实际开发过程中可以根据业务选择最适合的业务场景
Sender
package com.jiataoyuan.demo.rabbitmq.config;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* Created by Administrator on 2017/5/8 0008.
*/
@Component
public class Sender {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendData(String data){
if (null == data){
data = "data is null! Time: " + new Date();
}
System.out.println("Sender : " + data);
rabbitTemplate.convertAndSend("hello", data);
}
}
Receive
package com.jiataoyuan.demo.rabbitmq.config;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* @author TaoYuan
* @version V1.0.0
* @date 2018/4/21 0021
* @description description
*/
@Component
@RabbitListener(queues = "hello")
public class Receive {
@RabbitHandler
public void process(String hello) {
System.out.println("Receiver : " + hello);
}
}
Controller
package com.jiataoyuan.demo.rabbitmq.controller;
import com.jiataoyuan.demo.rabbitmq.config.Sender;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.Date;
/**
* @author TaoYuan
* @version V1.0.0
* @date 2018/4/21 0021
* @description description
*/
@RestController
@RequestMapping("/rabbit")
public class RabbitMQController {
@Resource
private Sender sender;
@GetMapping()
public String Main(){
return "<h1>hello RabbitMQ!</h1>";
}
@GetMapping("/send")
public String Send() throws Exception{
sender.sendData("Hello, This is OneToOne!");
return "Send OK!";
}
}
result
Sender : Hello, This is OneToOne!
Receiver : Hello, This is OneToOne!