生产者工程
1 添加MySource.java文件,把Source.java或Sink.java的代码抄来,改改
package com.test.shenchanzhe.service;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
/*
自定义消息通道
*/
public interface MySource {
//application.yml中引用此名称
String OUTPUT = "my_output";
@Output(MySource.OUTPUT)
MessageChannel output();
}
2 修改 MessageProducer.java 文件,注意注解的位置的代码
package com.test.shenchanzhe.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
/**
* 消息生产者
*/
@Component
@EnableBinding(MySource.class)
public class MessageProducer {
@Autowired
private MySource source;
/**
* 发送消息
*
* @param message
*/
public void send(String message) {
final boolean send = source.output().send(MessageBuilder.withPayload(message).build());
System.out.println(send);
}
}
3 修改 application.yml文件
消费者工程
1 添加 MySink.java 文件,把Source.java或Sink.java的代码抄来,改改
package com.test.xiaofeizhe.service;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.messaging.SubscribableChannel;
/*
自定义消息通道
*/
public interface MySink {
//application.yml中引用此名称
String INPUT = "my_input";
@Input(MySink.INPUT)
SubscribableChannel input();
}
2 修改 MessageConsumer.java 文件,注意注解的位置的代码
package com.test.xiaofeizhe.service;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;
/**
* 消息消费者
*/
@Component
@EnableBinding(MySink.class)
public class MessageConsumer {
/**
* 接收消息
*
* @param message
*/
@StreamListener(MySink.INPUT)
public void receive(String message) {
System.out.println("消息 = " + message);
}
}
3 修改 application.yml文件