RabbitMQ
在docker中運行rabbitmqjava
docker run -d -p 5672:5672 -p 8080:15672 rabbitmq:3-management
瀏覽器打開:http://10.202.203.29:8080/spring
默認用戶名/密碼都是guestdocker
在Admin頁面添加用戶瀏覽器
新添加的用戶是沒有權限的app
點擊用戶名進去,按提示添加權限ide
這樣就能夠在程序中訪問了。單元測試
建立spring boot 項目,添加pom依賴測試
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bus-amqp</artifactId> </dependency>
添加發送類Sender編碼
import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Date; @Component public class Sender { @Autowired private AmqpTemplate amqpTemplate; public void send(){ String context="hello "+new Date(); System.out.println("Sender: "+context); amqpTemplate.convertAndSend("hello",context); } }
添加接收類Receiverspa
import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class Receiver { @RabbitListener(queues = "hello") @RabbitHandler public void process(String hello){ System.out.println("Receiver: "+hello); } }
注意這裏的@RabbitListener(queues = "hello")不要加在類上,而是加在方法上,官方的教程這裏是錯誤的
添加配置類RabbitConfig
import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitConfig { @Bean public Queue helloQueue(){ return new Queue("hello"); } }
配置文件
spring.application.name=rabbitmq-hello spring.rabbitmq.host=10.202.203.29 spring.rabbitmq.port=5672 spring.rabbitmq.username=springcloud spring.rabbitmq.password=123456
單元測試
@RunWith(SpringRunner.class) @SpringBootTest public class RabbitmqHelloApplicationTests { @Autowired private Sender sender; @Test public void contextLoads() { sender.send(); } }
啓動應用,在RabbitMQ管理界面中查看鏈接
運行單元測試,能夠在控制檯看到結果
再查看管理頁面
開啓應用的接受監控後,能夠在rabbitmq管理界面直接發送消息,須要指定編碼格式
在控制檯能夠看到接收到了消息