Spring Cloud Stream RabbitMQ 簡單實現
阿新 • • 發佈:2018-12-07
參考官方文件: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