Spring Cloud Stream RabbitMQ 简单实现

参考官方文档:http://cloud.spring.io/spring-cloud-static/Finchley.SR1/single/spring-cloud.html#_rabbitmq_binder

环境:win10 rabbit 默认配置

一、添加依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>

二、配置文件

spring:
  application:
    name: rabbitmq-client
  cloud:
    stream:
      bindings:
        chen2018:  #通道名
          destination: chen-test #目的地
  rabbitmq:
    host: localhost
    port: 5672

三、构建消息发送者

  1.先创建通道

public interface ChenService {
  @Output("chen2018")
  MessageChannel chen();

}

  2.扫描接口

@EnableBinding(ChenService.class)

  3.发送消息类

   为了防止中文乱码加了消息头

@RestController
public class TestController {

  @Autowired
  private RabbitTemplate rabbitTemplate;

  @Autowired
  private ChenService chenService;

  @GetMapping("/send")
  public Boolean sendMsg(@RequestParam String msg){
    //获取MessageChanel
    MessageChannel messageChannel = chenService.chen();
    Map<String,Object> headers = new HashMap<>();
    headers.put("charset-encoding","UTF-8");
    headers.put("content-type",MediaType.TEXT_PLAIN_VALUE);
    return messageChannel.send(new GenericMessage<>(msg,headers));
  }
}

四、构建消息订阅者

  1.构建订阅通道

public interface ChenService {
  @Input("chen2018")
  SubscribableChannel chen();
}

  2.扫描接口

@EnableBinding(ChenService.class)

  3.多种编程模型根据实际情况选择

    @Autowired
	private ChenService chenService;

	@PostConstruct
	public void init(){//接口编程
		//获取Subscribe chanel
		SubscribableChannel subscribableChannel = chenService.chen();
		subscribableChannel.subscribe(message -> {
			MessageHeaders headers = message.getHeaders();
			String encoding = (String) headers.get("charset-encoding");
			String text = (String)headers.get("content-type");
			byte[] content = (byte[]) message.getPayload();
			try {
				System.out.println("接收到消息:"+ new String(content,encoding));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		});
	}
	@StreamListener("chen2018")
	public void onMessage(byte[] data){//注解编程
		System.out.println("onMessage(byte[]):"+data);
	}

	@StreamListener("chen2018")
	public void onMessage(String data){//注解编程
		System.out.println("onMessage(String):"+data);
	}

	@ServiceActivator(inputChannel = "chen2018") //Spring Integration注解
	public void onServiceActivator(String data){
		System.out.println("onServiceActivator(String):"+data);
	}

    建议:使用同一种编程模型
    相同的编程模型重复执行,不同的编程模型轮流执行

五、测试结果

访问:http://localhost:8088/send?msg=加油!fighting

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值