[Java] 纯文本查看 复制代码
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
/**
* 由于是基于spring boot test组件进行单元测试,需要构建一个TestApplication上下文
*/
@SpringBootApplication
@EnableRabbit
public class TestApplication {
public static void main(String[] args){
SpringApplicationBuilder builder = new SpringApplicationBuilder();
builder.environment(new StandardEnvironment());
builder.sources(TestApplication.class);
builder.main(TestApplication.class);
builder.run(args);
}
}
[Java] 纯文本查看 复制代码
import org.junit.Test;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class)
public class SpringBootMqSendTest{
private final static String EXCHANGE_NAME = "hello_fanout_1";
private final static String QUEUE_NAME = "hello_queue_1";
@Autowired
private RabbitAdmin rabbitAdmin;
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void testSend(){
FanoutExchange fanoutExchange = new FanoutExchange(EXCHANGE_NAME, false, false);
Queue queue = new Queue(QUEUE_NAME, false);
rabbitAdmin.declareExchange(fanoutExchange);
rabbitAdmin.declareQueue(queue);
rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(fanoutExchange));
Message message = new Message("hello world.".getBytes(), new MessageProperties());
rabbitTemplate.send(EXCHANGE_NAME, "", message);
}
}
[Java] 纯文本查看 复制代码
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class SpringBootMsqConsumer {
@RabbitListener(queues = "hello_queue_1")
public void receive(Message message) {
System.out.println("receive message:" + new String(message.getBody()));
}
}
[Java] 纯文本查看 复制代码
import org.junit.Test;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class)
public class SpringBootMqConsumerTest {
@Autowired
private SpringBootMsqConsumer springBootMsqConsumer;
@Test
public void testConsumer(){
}
}