Springboot集成RabbitMQ

一、简单使用

1、创建eureka注册中心

(1)创建项目模块

(2)pom文件

        <!--eureka-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <!--Eureka添加用户认证-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!--热部署依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

(3)文件application.yml配置

server:
    port: 8000

###服务名称
spring:
    application:
        name: eureka-center
    security:
        basic:
            enable: true #开启基于HTTP basic的认证
        user: #配置用户的账号信息
            name: zzq
            password: 123456

eureka:
    instance:
        hostname: localhost
    client:
        register-with-eureka: false #指定当前主机是否注册eureka server
        fetch-registry: false #指定当前主机是否从eureka server下载注册表
        service-url:
            #暴露eureka server服务地址
            defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka


(4)eureka登录验证

package com.zzq.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 高版本springcloud的丢弃了配置:
     * security:
     *   basic:
     *    enabled: true
     * 所以应该使用以下方式开
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Configure HttpSecurity as needed (e.g. enable http basic).
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
        http.csrf().disable();
        //注意:为了可以使用 http://${user}:${password}@${host}:${port}/eureka/ 这种方式登录,所以必须是httpBasic,
        // 如果是form方式,不能使用url格式登录
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }
}

(5)开启eureka

package com.zzq;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer //开启rureka服务
@SpringBootApplication
public class EurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }

}

(6)启动效果

2、创建mq模块

(1)创建项目模块

(2)配置pom文件,主要是添加spring-boot-starter-amqp的支持

<!--eureka-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--rabbitmq-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
            <version>1.5.2.RELEASE</version>
        </dependency>

(3)配置application.yml文件,文件配置rabbitmq的安装地址、端口以及账户信息

server:
  port: 8081

spring:
  application:
    name: 00-provider-8081  # 暴露微服务名称
  #链接eureka用户验证
  security:
    basic:
      enable: true #开启基于HTTP basic的认证
    user: #配置用户的账号信息
      name: zzq
      password: 123456

  rabbitmq:
    host: 112.74.216.57
    port: 5672
    username: admin
    password: admin

# 指定Eureka服务中心
eureka:
  client:
    service-url:
      defaultZone: http://zzq:123456@127.0.0.1:8000/eureka
      #defaultZone: http://eureka8100.com:8100/eureka,http://eureka8200.com:8200/eureka,http://eureka8300.com:8300/eureka
  # 指定当前客户端主机在注册中心的名称
  instance:
    instance-id: 00-provider-8081

(4)创建生成者

package com.zzq.rabbitMq;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 生成者
 */
@Component
public class Producer {

    @Autowired
    private AmqpTemplate rabbitmqTemplate;

    public void send(String content) {
        this.rabbitmqTemplate.convertAndSend("q_hello", content);
    }

}

(5)创建消费者

package com.zzq.rabbitMq;

import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "q_hello")
public class Consumer {

    @RabbitHandler
    public void process1(String hello) {
        System.out.println("Consumer:" + hello);
    }
}

(6)队列配置

package com.zzq.rabbitMq;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {
    @Bean
    public Queue helloQueue(){
        return new Queue("q_hello");
    }
}

(7)启动类

package com.zzq;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
public class ProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProviderApplication.class, args);
    }

}

(8)RabbitMqController

package com.zzq.rabbitMq;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RabbitMqController {
    @Autowired
    Producer producer;
    @RequestMapping("/mq")
    public void doSome() {
        producer.send("你好");
    }
}

(9)效果

http://localhost:8081/mq

二、主题模式

(1)生产者

package com.zzq.topic;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 生成者
 */
@Component
public class TopicProducer {

    @Autowired
    private AmqpTemplate rabbitmqTemplate;

    public void send1() {
        String context = "hi, i am message 1";
        System.out.println("Producer : " + context);
        this.rabbitmqTemplate.convertAndSend("myexchange", "topic.message", context);
    }


    public void send2() {
        String context = "hi, i am messages 2";
        System.out.println("Producer : " + context);
        this.rabbitmqTemplate.convertAndSend("myexchange", "topic.messages", context);
    }



}

(2)消费者

package com.zzq.fanout;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "q_fanout_A")
public class ComsumerA {

    @RabbitHandler
    public void process(String hello) {
        System.out.println("q_fanout_A  : " + hello + "/n");
    }
}
package com.zzq.topic;


import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "q_topic_messages")
public class Consumer2 {
    @RabbitHandler
    public void process(String hello) {
        System.out.println("Consumer2  : " + hello);
    }
}

(3)交换机绑定

package com.zzq.topic;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TopicRabbitConfig {

    final static String message = "q_topic_message";
    final static String messages = "q_topic_messages";

    @Bean
    public Queue queueMessage() {
        return new Queue(TopicRabbitConfig.message);
    }

    @Bean
    public Queue queueMessages() {
        return new Queue(TopicRabbitConfig.messages);
    }

    /**
     * 声明一个Topic类型的交换机
     * @return
     */
    @Bean
    TopicExchange exchange() {
        return new TopicExchange("myexchange");
    }

    /**
     * 绑定Q到交换机,并且指定routingKey
     * @param queueMessage
     * @param exchange
     * @return
     */
    @Bean
    Binding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange) {
        return BindingBuilder.bind(queueMessage).to(exchange).with("topic.message");
    }

    /**
     * #匹配一个或者多个词,*匹配一个词
     * @param queueMessages
     * @param exchange
     * @return
     */
    @Bean
    Binding bindingExchangeMessages(Queue queueMessages, TopicExchange exchange) {
        return BindingBuilder.bind(queueMessages).to(exchange).with("topic.#");
    }
}

(4)测试

package com.zzq.topic;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RabbitTopicMqController {
    @Autowired
    TopicProducer producer;

    @RequestMapping("/mq/topic/send1")
    public void send1() {
        producer.send1();
    }
    @RequestMapping("/mq/topic/send2")
    public void send2() {
        producer.send2();
    }
}

(5)效果

三、Fanout Exchange(订阅模式)

Fanout 就是我们熟悉的广播模式或者订阅模式,给Fanout交换机发送消息,绑定了这个交换机的所有队列都收到这个消息

(1)配置队列,绑定交换机

package com.zzq.fanout;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FanoutRabbitConfig {

    @Bean
    public Queue aMessage() {
        return new Queue("q_fanout_A");
    }

    @Bean
    public Queue bMessage() {
        return new Queue("q_fanout_B");
    }

    @Bean
    public Queue cMessage() {
        return new Queue("q_fanout_C");
    }

    @Bean
    FanoutExchange fanoutExchange() {
        return new FanoutExchange("myfanoutExchange");
    }

    @Bean
    Binding bindingExchangeA(Queue aMessage, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(aMessage).to(fanoutExchange);
    }

    @Bean
    Binding bindingExchangeB(Queue bMessage, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(bMessage).to(fanoutExchange);
    }

    @Bean
    Binding bindingExchangeC(Queue cMessage, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(cMessage).to(fanoutExchange);
    }
}

(2)生产者

package com.zzq.fanout;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class FanoutProducer {
    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send() {
        String context = "hi, fanout msg ";
        System.out.println("Sender : " + context);
        this.rabbitTemplate.convertAndSend("myfanoutExchange","", context);
    }
}

(3)消费者

创建3个消费者

package com.zzq.fanout;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "q_fanout_A")
public class ComsumerA {

    @RabbitHandler
    public void process(String hello) {
        System.out.println("ComsumerA  : " + hello + "/n");
    }
}

 

package com.zzq.fanout;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "q_fanout_B")
public class ComsumerB {

    @RabbitHandler
    public void process(String hello) {
        System.out.println("q_fanout_B  : " + hello + "/n");
    }
}
package com.zzq.fanout;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "q_fanout_C")
public class ComsumerC {

    @RabbitHandler
    public void process(String hello) {
        System.out.println("q_fanout_C  : " + hello + "/n");
    }
}

(4)测试

package com.zzq.fanout;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FanoutController {
    @Autowired
    private FanoutProducer producer;

    @RequestMapping("/mq/fanout")
    public void send1() throws Exception {
        producer.send();
    }
}

结果如下,三个消费者都收到消息:

q_fanout_A  : hi, fanout msg /n
q_fanout_B  : hi, fanout msg /n
q_fanout_C  : hi, fanout msg /n

推荐学习 :https://blog.csdn.net/hellozpc/article/details/81436980

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

2014Team

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值