springboot整合RabbitMQ及使用

RabbitMQ跨语言消息插件整合使用

步骤

  1. 导入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lmh</groupId>
    <artifactId>spring-boot-09</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-09</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

其中要使用maven的中央仓库,在maven安装路径下setting.xml中配置mirror标签

<mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |>-->
 <!--   <mirror>
      <id>nexus-aliyun</id>
      <mirrorOf>central</mirrorOf>
      <name>Nexus aliyun</name>
      <url>http://maven.aliyun.com/nexus/content/groups/public</url>
    </mirror>-->
	
	<mirror>
      <id>repo1</id>
      <mirrorOf>central</mirrorOf>
      <name>Human Readable Name for this Mirror</name>
      <url>http://insecure.repo1.maven.org/maven2</url>
    </mirror>
     
  </mirrors>

个人测试是先使用的阿里云仓库,但是依赖没有完全导入,具体原因还不清楚,建议使用中央仓库,有知道原因的望交流

2.整合RabbitMQ原理及源码解析
springboot提供自动配置类源码中

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ RabbitTemplate.class, Channel.class })
@EnableConfigurationProperties(RabbitProperties.class)
@Import(RabbitAnnotationDrivenConfiguration.class)
public class RabbitAutoConfiguration {

	@Configuration(proxyBeanMethods = false)
	@ConditionalOnMissingBean(ConnectionFactory.class)
	protected static class RabbitConnectionFactoryCreator {

		@Bean
		public CachingConnectionFactory rabbitConnectionFactory(RabbitProperties properties,
				ObjectProvider<ConnectionNameStrategy> connectionNameStrategy) throws Exception {
			PropertyMapper map = PropertyMapper.get();
			CachingConnectionFactory factory = new CachingConnectionFactory(
					getRabbitConnectionFactoryBean(properties).getObject());
			map.from(properties::determineAddresses).to(factory::setAddresses);
			map.from(properties::isPublisherReturns).to(factory::setPublisherReturns);
			map.from(properties::getPublisherConfirmType).whenNonNull().to(factory::setPublisherConfirmType);
			RabbitProperties.Cache.Channel channel = properties.getCache().getChannel();
			map.from(channel::getSize).whenNonNull().to(factory::setChannelCacheSize);
			map.from(channel::getCheckoutTimeout).whenNonNull().as(Duration::toMillis)
					.to(factory::setChannelCheckoutTimeout);
			RabbitProperties.Cache.Connection connection = properties.getCache().getConnection();
			map.from(connection::getMode).whenNonNull().to(factory::setCacheMode);
			map.from(connection::getSize).whenNonNull().to(factory::setConnectionCacheSize);
			map.from(connectionNameStrategy::getIfUnique).whenNonNull().to(factory::setConnectionNameStrategy);
			return factory;
		}

提供连接工厂CachingConnectionFactory,提供了端口等等,由参数RabbitProperties类指定
其RabbitProperties源码可查看属性,在application.properties文件修改

spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
#public void setVirtualHost(String virtualHost) {
#		this.virtualHost = "".equals(virtualHost) ? "/" : virtualHost;
#	}
#RabbitProperties源码,可的默认访问地址,也可以自定义
#spring.rabbitmq.virtual-host=

3.自动配置提供了RabbitTemplate操作消息发送接收,和AmqpAdmin控制RabbitMQ队列,exchange(转换器),binding(绑定)

@Bean
		@ConditionalOnSingleCandidate(ConnectionFactory.class)
		@ConditionalOnMissingBean(RabbitOperations.class)
		public RabbitTemplate rabbitTemplate(RabbitTemplateConfigurer configurer, ConnectionFactory connectionFactory) {
			RabbitTemplate template = new RabbitTemplate();
			configurer.configure(template, connectionFactory);
			return template;
		}

		@Bean
		@ConditionalOnSingleCandidate(ConnectionFactory.class)
		@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic", matchIfMissing = true)
		@ConditionalOnMissingBean
		public AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory) {
			return new RabbitAdmin(connectionFactory);
		}

	}

4.测试

import com.sun.org.apache.xpath.internal.objects.XObject;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@SpringBootTest
class SpringBoot09ApplicationTests {
@Autowired
    RabbitTemplate rabbitTemplate;
@Autowired
    AmqpAdmin amqpAdmin;
//发送数据
    @Test
    void contextLoads() {
        //message需要自己构造一个,定义消息内容和消息头
        //rabbitTemplate.send(exchange,routeKey,message);

        //object默认当成消息体,只需要传入要发送的对象,自动化序列(默认为jdk序列化)发送给rabbitmq
        //rabbitTemplate.convertAndSend(exchange,routeKey, Object);

        Map<String,Object> map=new HashMap<>();
        map.put("msg","这是第一个消息");
        map.put("data", Arrays.asList("helloworld",123,true));
        rabbitTemplate.convertAndSend("exchange.direct","lmh",map);
    }
    //接受数据测试
    @Test
    public void receive()
    {
        Object o=rabbitTemplate.receiveAndConvert("lmh");
        System.out.println(o);
    }

    //测试AmqpAdmin
    @Test
    public void admin(){
        //创建交换器,具体属性见Exchange源码
        amqpAdmin.declareExchange(new DirectExchange("amqpAdmin.exchange"));
        //创建队列,具体属性见Queue源码
        amqpAdmin.declareQueue(new Queue("lmh.queue"));
        //创建绑定,具体属性见Binding源码
        amqpAdmin.declareBinding(new Binding("lmh.queue", Binding.DestinationType.QUEUE,"amqpAdmin.exchange","lmh.queue",null));


    }
    @Test
    public void admin1(){
        //删除操作
        amqpAdmin.deleteExchange("amqpAdmin.exchange");
    }

}

6.可以开启监听功能在主程序要开启RabbitMQ的注解

@EnableRabbit//开启基于注解的RabbitMQ
@SpringBootApplication
public class SpringBoot09Application {

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

}

再在service里方法上加上注解@RabbitListener并指定队列名

@Service
public class receiveService {
    @RabbitListener(queues = "lmh.news")
    public void receive(Message message){
        System.out.println(message.getBody());
        System.out.println(message.getMessageProperties());
        System.out.println(message);
    }
}

7.可以写自己的配置类,用于json序列化的,便于观察数据信息
RabbitTemplate源码中决定message的序列化代码

private MessageConverter messageConverter = new SimpleMessageConverter();

SimpleMessageConverter源码中可以看出默认使用jdk的

try {
                    content = SerializationUtils.deserialize(this.createObjectInputStream(new ByteArrayInputStream(message.getBody()), this.codebaseUrl));
                } catch (IllegalArgumentException | IllegalStateException | IOException var7) {
                    throw new MessageConversionException("failed to convert serialized Message content", var7);
                }

这可以使得MessageConvert new一个自定义的,例如json的代码如下

@Configuration
public class RabbitConfig {
    /**
     * 序列化message消息转为json有帮助观看,接受发送都生效
     * @return
     */
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }
}

在测试代码块加上下面内容

 Student student=new Student();
        student.setAge(18);
        student.setName("张三");
        student.setPhoneNum("110");
        rabbitTemplate.convertAndSend("exchange.direct","lmh",student);

结果如下
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值