- 消息服务
- ActiveMQ安装
- SpringBoot整合ActiveMQ
- RabbitMQ简介并安装
- SpringBoot整合RabbitMQ
- 消息服务
- ActiveMQ安装
- SpringBoot整合ActiveMQ
JMS===Java Message Service[发布者、订阅者]===java平台,无法跨平台(ActiveMQ) RabbitMQ\ActiveMQ\kafaka http://activemq.apache.org/components/classic/download
解压:
tar -zxvf apache-activemq-5.15.4-bin.tar.gz
进入解压目录,直接启动
cd apache-activemq-5.15.4
/root.apache-activemq-5.15.4/bin/env
./bin.activemq start
http://localhost:8161 //后台管理端口,用户名密码都是admin
创建项目,添加依赖Web\Messaging里面的 Spring for Apache ActiveMQ 5依赖 在application.properties中配置ActiveMQ相关信息
spring.activemq.broker-url=tcp://localhost:61616 //端口号
spring.activemq.packages.trust-all=true
spring.activemq.user=admin
spring.activemq.password=admin
在启动类中加入一个Bean
@Bean
Queue queue() {
return new ActiveMQQueue("zenghao,hello");
}
创建一个Message类
public class Message implements Serizlizable{
private String content; //消息的主体
private Date sendDate; //消息的发送日期
get()/set()
toString()
.....
}
创建一个JMSComponent
@Component
public class JmsComponent {
@Autowired
JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
Queue queue;
//生产者
piblic void send(Message message) {
jmsMessagingTemplate.convertAndSend(this.queue,message); //发消息
}
//消费者
@JmsListener(destination="zenghao,hello")
public void recieve(Message msg) {
System.out.println(msg);
}
}
测试
public class ActivemqApplicationTests {
@Autowired
JmsComponent jmsComponent;
@Test
public void contextLoads() {
Message message = new Message();
message.setContent("hello,zenghao");
message.setSendDate(new Date());
jmsComponent.send(message);
}
}
- RabbitMQ简介并安装
docker安装 http://hub.docker.con/_/rabbitmq
$docker run -d --hostname my-rabbit --name some-rabbit -P rabbitmq:3-management
docker ps 查看是否启动
默认用户名密码,guest
- Spring整合RabbitMQ
创建项目,勾选web依赖和Messaging下的 Spring for RabbitMQ依赖 配置application,properties
spring.rabbitmq.hsot:localhost
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.post=32771 //docker里面查看
创建一个config目录下创建一个RabbitDirectConfig
@Configuration
public class RabbitDirectConfig {
public final static String DIRBCTNAME="zenghao-direct";
@Bean
Queue queue(){
return new Queue("hello,zenghao");
}
@Bean
DirectExchange directExchange (){
return new DirectExchange (DIRBCTNAME,true,false); //重启是否有效,长期不用是否删除
}
@Bean //添加绑定上面两个在一起
Binding binding (){
return BindingBuilder.bind(queue()).to(directExchange()).with("direct");;
}
}
创建消费者,receiver目录下创建DirectReceiver
@Component
public class DirectReceiver {
@RabbitListener(queues="hello,zenghao")
public void handlerl(String msg) {
System.out.println("handler>>>"+msg);
}
}
Test:
public class RabbitmqApplicationTests {
@Autowired
RabbitTemplate rabbitTemplate;
@Test
public void test(){
rabbitTemplate.convertAndSend(routingKey:"hello.zenghao",object:"hellomzenghaohaohaoaho");
}
}