文章目录
1 direct
1.1 生产者
1.1.1 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
1.1.2 编写配置文件
spring:
application:
name: biz-publisher
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
# publisher-confirms: true
publisher-returns: true
publisher-confirm-type: correlated
server:
port: 8071
1.1.3 编写配置类(指定了交换机)
package fastwave.cloud.demo.fastwavebizpublisher.config;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BlogConfig {
@Bean
TopicExchange BlogExchange()
{
return new TopicExchange("BlogExchange");
}
}
1.1.4 编写controller(发送到哪个交换机,以及指定key)
package fastwave.cloud.demo.fastwavebizpublisher.controller;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("amqp")
public class AmqpController {
@Autowired
RabbitTemplate template;
@GetMapping("/direct")
public String sendEmail(@RequestParam Map<String, Object> params)
{
String msg = params.get("msg").toString();
template.convertAndSend("EmailExchange", "EmailRouting", msg);
return "OK";
}
}
1.2消费者
1.2.1 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
1.2.2 编写配置文件
spring:
application:
name: biz-subscriber
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
server:
port: 8072
1.2.3 编写配置类(指定了交换机,队列以及绑定交换机和队列)
package fastwave.cloud.demo.fastwavebizsubscriber.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class EmailConfig {
@Bean
DirectExchange EmailExchange()
{
return new DirectExchange("EmailExchange");
}
@Bean
Queue EmailQueue()
{
return new Queue("EmailQueue");
}
@Bean
Binding BindEmail()
{
return BindingBuilder.bind(EmailQueue()).to(EmailExchange()).with("EmailRouting");
}
}
1.2.4 编写service(@RabbitListener进行监听)
package fastwave.cloud.demo.fastwavebizsubscriber.services;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class EmailReceiver {
@RabbitListener(queues = "EmailQueue")
public void receiver(String msg)
{
System.out.println("收到的消息是:" + msg);
}
}
1.3 测试
1 启动消费者 和生产者
2 调用生产端的接口:
3