SpringBoot integration and connection to Redis cluster

The first step is to create a new project maven project and add dependencies

 

(1) The version of SpringBoot used in this article is as follows

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

 

(2) Add Redis related dependencies

Copy code

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

Copy code

 

The second step is to add redis related configuration to application.yml

Copy code

spring: 
  application: 
    name: redis-cluster 
  redis: 
    cluster: 
      nodes: 192.168.0.102:6379,192.168.0.103:6379,192.168.0.105:6379 
      max-redirects: 6 
redis: 
  timeout: 10000 #Client timeout unit is milliseconds The default is 2000 
  maxIdle: 300 
  #Maximum number of idle maxTotal: 1000 #Control how many jedis instances can be allocated to a pool to replace the redis.maxActive above, if it is jedis 2.4, use this attribute 
  maxWaitMillis: 1000 #Maximum connection waiting time . If this time is exceeded, an exception will be received. Set to -1 for unlimited. 
  minEvictableIdleTimeMillis: 300000 #The minimum idle time of the connection defaults to 1800000 milliseconds (30 minutes) 
  numTestsPerEvictionRun: 1024 #The maximum number of connections released each time, the default is 3 
  timeBetweenEvictionRunsMillis: 30000 #The time interval of the eviction scan (milliseconds) If it is a negative number, it will not run 
  Evict the thread, default -1 testOnBorrow: true #Whether to check before removing the connection from the pool, if the check fails, remove the connection from the pool and try to remove another
  testWhileIdle: true #Check validity when idle, default false 
  password: 123456 #Password 
server: 
  port: 8080

Copy code

 

The third step is to write the configuration class

Copy code

package com.qxj.redis;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisClusterConfig {

    @Value("${spring.redis.cluster.nodes}")
    private String clusterNodes;
    @Value("${spring.redis.cluster.max-redirects}")
    private int maxRedirects;
    @Value("${redis.password}")
    private String password;
    @Value("${redis.timeout}")
    private int timeout;
    @Value("${redis.maxIdle}")
    private int maxIdle;
    @Value("${redis.maxTotal}")
    private int maxTotal;
    @Value("${redis.maxWaitMillis}")
    private int maxWaitMillis;
    @Value("${redis.minEvictableIdleTimeMillis}") 
    private int minEvictableIdleTimeMillis;
    @Value("${redis.numTestsPerEvictionRun}")
    private int numTestsPerEvictionRun;
    @Value("${redis.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;
    @Value("${redis.testOnBorrow}")
    private boolean testOnBorrow;
    @Value("${redis.testWhileIdle}")
    private boolean testWhileIdle;
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    public JedisPoolConfig getJedisPoolConfig() {
    @Bean
     */
     * @return JedisPoolConfig
     *
     * Redis connection pool configuration

    /**
        // Maximum idle number 
        jedisPoolConfig.setMaxIdle(maxIdle); 
        // The maximum number of database connections in the connection pool 
        jedisPoolConfig.setMaxTotal(maxTotal);
        // The maximum waiting time for establishing a connection 
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); 
        // The minimum idle time for eviction connection is 1.800000 milliseconds (30 minutes) by 
        default jedisPoolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); 
        // The maximum number of evictions during each eviction check If it is a negative number, it is: 1/abs(n), default 3 
        jedisPoolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun); 
        // Time interval of eviction scan (milliseconds) If it is negative, the eviction thread will not be run, the default is -1 
        jedisPoolConfig.setTimeBetweenEvictionRunsMillis( timeBetweenEvictionRunsMillis); 
        // Whether to check before removing the connection from the pool, if the check fails, remove the connection from the pool and try to take out another 
        jedisPoolConfig.setTestOnBorrow(testOnBorrow); 
        // Check validity when idle, default false 
        jedisPoolConfig .setTestWhileIdle(testWhileIdle); 
        return jedisPoolConfig;
    }

    /**
     * Redis集群的配置
     * 
     * @return RedisClusterConfiguration
     */
    @Bean
    public RedisClusterConfiguration redisClusterConfiguration() {
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
        // Set<RedisNode> clusterNodes
        String[] serverArray = clusterNodes.split(",");
        Set<RedisNode> nodes = new HashSet<RedisNode>();
        for (String ipPort : serverArray) {
            String[] ipAndPort = ipPort.split(":");
            nodes.add(new RedisNode(ipAndPort[0].trim(), Integer.valueOf(ipAndPort[1])));
        }
        redisClusterConfiguration.setClusterNodes(nodes);
        redisClusterConfiguration.setMaxRedirects(maxRedirects);
        redisClusterConfiguration.setPassword(RedisPassword.of(password));
        return redisClusterConfiguration;
    }

    /**
     * redis连接工厂类
     * 
     * @return JedisConnectionFactory
     */
    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        // 集群模式
        JedisConnectionFactory factory = new JedisConnectionFactory(redisClusterConfiguration(), getJedisPoolConfig());
        return factory;
    }

    /**
     * Instantiate RedisTemplate object 
     * 
     * @return RedisTemplate<String, Object>
     */
    @Bean 
    public RedisTemplate<String, Object> redisTemplate() { 
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); 
        // Template initialization 
        initDomainRedisTemplate(redisTemplate); 
        return redisTemplate; 
    } 

    /** 
     * Setting the serialization method of storing data in redisUsing the default serialization will cause key garbled 
     */ 
    private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate) { 
        // Enable redis database transaction support 
        redisTemplate.setEnableTransactionSupport(true); 
        redisTemplate .setConnectionFactory(jedisConnectionFactory());
 
        // If Serializer is not configured, String is used by default when storing. If the User type is used for storage, it will prompt an error User can't cast to
        // String! 
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); 
        redisTemplate.setKeySerializer(stringRedisSerializer); 
        // The hash key also uses the String serialization method 
        redisTemplate.setHashKeySerializer(stringRedisSerializer); 

        // jackson serialization object setting 
        Jackson2JsonRedisSerializer<RedisRedisSerializer> Jackson2JsonRedisSerializer new >( 
                Object.class); 
        ObjectMapper om = new ObjectMapper();  
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 
        jackson2JsonRedisSerializer.setObjectMapper(om); 

        // value serialization method adopts jackson
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        redisTemplate.afterPropertiesSet();
    }
}

Copy code

 

The fourth step is to write the Controller test class

Copy code

package com.qxj.application;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private RedisTemplate<String, Object> template;

    @RequestMapping("/test")
    public String test() {
        template.opsForValue().set("demo", "hello world! 你好,世界");
        String str = (String) template.opsForValue().get("demo");
        return str;
    }

}

References: https://blog.csdn.net/WYA1993/article/details/88046628

https://www.cnblogs.com/wps54213/p/12608777.html

 

 

Use the built redis cluster in springboot-lettuce mode

Add redis and connection pool dependency

   <!--redis连接池 start-->
       <dependency>
           <groupId>org.apache.commons</groupId>
           <artifactId>commons-pool2</artifactId>
       </dependency>
       <!--redis连接池 end-->

       <!--redis start-->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-data-redis</artifactId>
           <version>2.2.6.RELEASE</version>
       </dependency>
       <!--redis end-->

Configure the connection pool and sentinel in the configuration file

ip: 39.97.234.52
spring:
  redis:
    lettuce:
      pool:
        max-active: 10
        max-idle: 8
        max-wait: -1ms
        min-idle: 0
    sentinel:
      master: mymaster
      nodes: ${ip}:26379,${ip}:26380,${ip}:26381
    password: test@dbuser2018

Add the redis configuration class and modify the default redis serialization method of springboot

@Configuration
public class RedisConfig {
    /**
     * 把任何数据保存到redis时,都需要进行序列化,默认使用JdkSerializationRedisSerializer进行序列化。
     * 默认的序列化会给所有的key,value的原始字符前,都加了一串字符(例如:\xAC\xED\x00\),不具备可读性
     * 所以需要配置jackson序列化方式
     */
    @Bean
    public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory factory){
        RedisTemplate<String,Object> template=new RedisTemplate<>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        //key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        //value采用jackson序列化方式
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //hash的key采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        //hash的value采用String的序列化方式
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

Create redis service

    @Service
    public class RedisServiceImpl implements RedisService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean put(String key, Object value, long seconds) throws JsonProcessingException {
        redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
        return true;
    }

    @Override
    public <T> T get(String key, Class<T> clazz) throws IOException {
        Object o = redisTemplate.opsForValue().get(key);
        if (o != null) {
            String json = String.valueOf(o);
            T t = JsonUtil.stringToObject(json, clazz);
            return t;
        }
        return null;
    }
    }

Create redisController to test redis service

    @RestController
    public class RedisController {

        @Autowired
        private RedisService redisService;

        @PostMapping(value = "put")
        public String put(String key,String value,long seconds){

            redisService.put(key,value,seconds);
            return "ok";
        }

        @GetMapping(value = "get")
        public Object get(String key){

            Object o=redisService.get(key);
            if(o!=null){
                return String.valueOf(o);
            }
            return "not_ok";
        }
    }

Guess you like

Origin blog.csdn.net/u014748504/article/details/108188167