版本Edgware.SR4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
application.properties
spring.rabbitmq.port=5672
spring.rabbitmq.virtualHost=/
spring.rabbitmq.host=192.168.74.164
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
生产者
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
public interface RefreshChannelOutput {
String OUTPUT = "refresh_channel_output";
@Output(OUTPUT)
MessageChannel messageOutput();
}
生产者添加配置文件
默认情况是topic 模式,绑定交换机,路由
spring.cloud.stream.bindings.refresh_channel_output.destination=ticket_bus_exchange
spring.cloud.stream.rabbit.bindings.refresh_channel_output.producer.routing-key-expression='refresh_channel'
消息发送,使用直接注入到其它类就行了
@Autowired
private RabbitmqProducer sendMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
@EnableBinding({ RefreshChannelOutput.class})
public class RabbitmqProducer {
@Autowired
@Output(RefreshChannelOutput.OUTPUT)
private MessageChannel refreshChannelChannel;
public void sendResChannel(String message) {
refreshChannelChannel.send(MessageBuilder.withPayload(message).build());
}
}
消费者
添加配置文件
绑定交换机,路由,消费者个数,消息格式
spring.cloud.stream.bindings.refresh_channel.destination=ticket_bus_exchange
spring.cloud.stream.bindings.refresh_channel.contentType=text/plain
spring.cloud.stream.bindings.refresh_channel.consumer.concurrency=1
spring.cloud.stream.rabbit.bindings.refresh_channel.consumer.bindingRoutingKey=refresh_channel
添加类
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.messaging.SubscribableChannel;
public interface RefreshChannelInput {
String INPUT = "refresh_channel";
@Input(RefreshChannelInput.INPUT)
SubscribableChannel input();
}
消息接收
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import com.hhly.ticket.cms.rabbit.input.MonitorInput;
import com.hhly.ticket.cms.rabbit.input.RefreshChannelInput;
@EnableBinding({RefreshChannelInput.class})
public class RabbitmqReceiver {
@StreamListener(RefreshChannelInput.INPUT)
public void refreshCahnnel(Object playload) {
System.out.println(playload.toString());
}
}