zoukankan      html  css  js  c++  java
  • 基于Redis的消息队列使用:spring boot2.0整合redis

    一 . 引入依赖

    <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>springboot.redis</groupId>
        <artifactId>springboot-redis</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.1.RELEASE</version>
            <relativePath />
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
        <!-- 上边引入 parent,因此 下边无需指定版本 -->
        <!-- 包含 mvc,aop 等jar资源 -->
        <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>
        </dependency>
    
        <!-- 热部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>
    
        <!--spring模板引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
                <version>2.0.4.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-pool2</artifactId>
                <version>2.6.0</version>
            </dependency>
    
            <!-- jackson序列化 -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
            </dependency>
    
    
        </dependencies>
    
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <!-- 没有该配置,devtools 不生效 -->
                        <fork>true</fork>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
    
    </project>
    View Code

    二 . application.properties

    # Redis数据库索引(默认为0)
    
    spring.redis.database=0
    
    # Redis服务器地址
    
    spring.redis.host=127.0.0.1
    
    # Redis服务器连接端口
    
    spring.redis.port=6379
    
    # Redis服务器连接密码(默认为空)
    
    spring.redis.password=
    
    # 连接池最大连接数(使用负值表示没有限制)
    
    spring.redis.jedis.pool.max-active=200
    
    # 连接池最大阻塞等待时间(使用负值表示没有限制)
    
    spring.redis.jedis.pool.max-wait=-1
    
    # 连接池中的最大空闲连接
    
    spring.redis.jedis.pool.max-idle=10
    
    # 连接池中的最小空闲连接
    
    spring.redis.jedis.pool.min-idle=0
    
    # 连接超时时间(毫秒)
    
    spring.redis.timeout=1000 
    
    redis.queue=message
    View Code

    三 . RedisTemplate 的bean定制化

         通过源码可以看出,SpringBoot自动帮我们在容器中生成了一个RedisTemplate和一个StringRedisTemplate。但是,这个RedisTemplate的泛型是<Object,Object>,写代码不方便,需要写好多类型转换的代码;我们需要一个泛型为<String,Object>形式的RedisTemplate。并且,这个RedisTemplate没有设置数据存在Redis时,key及value的序列化方式。

            看到@ConditionalOnMissingBean注解后,就知道如果Spring容器中有了RedisTemplate对象了,这个自动配置的RedisTemplate不会实例化。因此我们可以直接自己写个配置类,配置RedisTemplate。
    package com.zjt.config;
    
    
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    @Configuration
    public class RedisConfig {
    
        @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
            RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
            template.setConnectionFactory(factory);
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
            ObjectMapper om = new ObjectMapper();
            om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            jackson2JsonRedisSerializer.setObjectMapper(om);
            StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
            // key采用String的序列化方式
            template.setKeySerializer(stringRedisSerializer);
            // hash的key也采用String的序列化方式
            template.setHashKeySerializer(stringRedisSerializer);
            // value序列化方式采用jackson
            template.setValueSerializer(jackson2JsonRedisSerializer);
            // hash的value序列化方式采用jackson
            template.setHashValueSerializer(jackson2JsonRedisSerializer);
            template.afterPropertiesSet();
            return template;
    
        }
    
    }
    View Code

    四 . 消息的发布者

    package com.zjt.redis;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Component;
    
    /**
     *  消息的发布者
     */
    @Component
    public class SendService {
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        public void sendMessage(String message){
            try{
                redisTemplate.convertAndSend("myChannel", message);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    View Code

    五 . 消息的消费者

    package com.zjt.redis;
    
    import org.springframework.stereotype.Component;
    
    /**
     *  消息的消费者
     */
    @Component
    public class Receiver {
    
        public void receiveMessage(String message){
            System.out.println("Receive: " + message);
        }
    
    }
    View Code

    六 . 配置类

    package com.zjt.redis.config;
    
    import com.zjt.redis.Receiver;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.listener.PatternTopic;
    import org.springframework.data.redis.listener.RedisMessageListenerContainer;
    import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
    
    @Configuration
    //@AutoConfigureAfter({Receiver.class})
    public class SubscriberConfig {
    
        @Autowired
        Receiver receiver;
    
        /**
         * 注入消息监听适配器
         */
    //    @Bean
    ////    public MessageListenerAdapter getMessageListenerAdapter(Receiver receiver){
    ////        return new MessageListenerAdapter(receiver, "receiveMessage");
    ////    }
        @Bean
        public MessageListenerAdapter getMessageListenerAdapter(){
            return new MessageListenerAdapter(receiver, "receiveMessage");
        }
    
        /**
         *
         *  注入消息的监听容器
         */
        @Bean
        public RedisMessageListenerContainer getRedisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory, MessageListenerAdapter messageListenerAdapter){
            RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
            redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
            redisMessageListenerContainer.addMessageListener(messageListenerAdapter, new PatternTopic("myChannel"));
            return redisMessageListenerContainer;
        }
    
    
    }
    View Code

    七 . 测试类

    package com.zjt.contrller;
    
    import com.zjt.redis.SendService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class SubscriberController {
    
        @Autowired
        private SendService sendService;
    
        @PostMapping("sendMessage")
        public void send(@RequestParam("message") String message){
            sendService.sendMessage(message);
        }
    }
    View Code

    如上,访问请求即可实现后台从redis消息队列获取消息。

  • 相关阅读:
    安装archlinux的另辟蹊径的命令及心得
    deepin15.11安装N卡驱动,实测!!!(可解决N卡电脑关机卡屏)
    js实现简单下载
    微信公众号的开发 该公众号提供的服务出现故障,请稍后再试
    线程池的创建
    多线程,生产者消费者模型(生产馒头,消费馒头)
    第1章 Java IO系统 下
    T01章[Java IO系统] 作业
    第1章 Java IO系统
    用集合实现一个控制台版的学生管理系统
  • 原文地址:https://www.cnblogs.com/zjting/p/11366706.html
Copyright © 2011-2022 走看看