Based on the message queue using the Redis: spring boot2.0 integration redis

A. Introducing dependence

<?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>. 8-UTF </ project.build.sourceEncoding > 
        < project.reporting.outputEncoding > UTF-. 8 </ project.reporting.outputEncoding > 
        < the java.version > 1.8 </ the java.version > 
    </ Properties > 

    < Dependencies > 
    <! - on top of the introduction of parent, and therefore you do not need to specify the version below -> 
    <! - include mvc, aop jar and other resources -> 
    < 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

Two. Application.properties

# Redis database indexes (default is 0) 

spring.redis.database = 0 

# Redis server address 

spring.redis.host = 127.0.0.1 

# Redis server port 

spring.redis.port = 6379 

# Redis server connection password (default is empty ) 

spring.redis.password = 

# connection pool maximum number of connections (negative values no limit) 

spring.redis.jedis.pool.max-200 is Active = 

# latency connection pool maximum blocking (negative values no limit) 

Spring -1 = the wait-.redis.jedis.pool.max 

# connection pool maximum idle connection 

spring.redis.jedis.pool.max-iDLE = 10 

# minimum connection pool idle connections 

spring.redis.jedis.pool. IDLE = 0-min 

# connection time (ms) 

spring.redis.timeout = 1000 

redis.queue = Message
View Code

Three. RedisTemplate of bean customization

     As can be seen by the source, SpringBoot generated automatically help us in a container RedisTemplate and a StringRedisTemplate. However, this RedisTemplate generic is <Object, Object>, write code that is not convenient, you need to write a lot of code type conversion; we need is a generic <String, Object> form RedisTemplate. Further, this RedisTemplate there is not provided Redis data, key and value of serialization.

        See @ConditionalOnMissingBean the notes, you know if the Spring container with RedisTemplate objects, this automatic configuration RedisTemplate not be instantiated . Therefore, we can directly write their own configuration class configuration 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 new StringRedisSerializer ();
         // key using the serialization String 
        template.setKeySerializer (stringRedisSerializer);
         // the hash key is also used String the serialization 
        template.setHashKeySerializer (stringRedisSerializer);
         // value serialization using Jackson 
        template.setValueSerializer (jackson2JsonRedisSerializer);
         // the hash value of the use of serialization Jackson 
        template.setHashValueSerializer (jackson2JsonRedisSerializer); 
        template.afterPropertiesSet (); 
        return Template; 

    } 

}
View Code

IV. Publishers message

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

V. consumer message

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

VI. Configuring class

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; 

    / ** 
     * injection adapter listens message 
     * / 
//     @Bean 
////     public getMessageListenerAdapter The MessageListenerAdapter (Receiver Receiver) { 
////         return new new The MessageListenerAdapter (Receiver, "receiveMessage"); 
////     } 
    @Bean
     public the MessageListenerAdapter getMessageListenerAdapter () {
         return  new new the MessageListenerAdapter (Receiver, "receiveMessage" ); 
    } 

    / ** 
     * 
     listening * injection container message 
     * / 
    @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

VII. Test class

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

As above, the access request message can achieve a background acquired from the message queue redis.

 

 

 

 

Guess you like

Origin www.cnblogs.com/zjting/p/11366706.html