SpringBoot集成redis集群

1、添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <!-- 过滤lettuce,使用jedis作为redis客户端 -->
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>
<!-- 用来序列化的 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.62</version>
</dependency>

 

2、新增redis配置

在application.properties中添加以下配置

#redis配置
spring.redis.database=0
#集群节点
spring.redis.cluster.nodes=127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384
#连接池最大连接数
spring.redis.jedis.pool.max-active=10  
#连接池中最大空闲连接数
spring.redis.jedis.pool.max-idle=8 
#连接池最大等待阻塞时间
spring.redis.jedis.pool.max-wait=-1
#连接池中最小空闲数
spring.redis.jedis.pool.min-idle=0
#访问超时时间
spring.redis.timeout=5000
#密码,如果有设置密码
#spring.redis.password=xxxx

 

3、配置RedisTemplate

  1 package com.demo.redis.config;
  2 
  3 import lombok.extern.slf4j.Slf4j;
  4 import org.springframework.beans.factory.annotation.Qualifier;
  5 import org.springframework.beans.factory.annotation.Value;
  6 import org.springframework.cache.CacheManager;
  7 import org.springframework.context.annotation.Bean;
  8 import org.springframework.context.annotation.Configuration;
  9 import org.springframework.data.redis.cache.RedisCacheConfiguration;
 10 import org.springframework.data.redis.cache.RedisCacheManager;
 11 import org.springframework.data.redis.connection.RedisClusterConfiguration;
 12 import org.springframework.data.redis.connection.RedisNode;
 13 import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
 14 import org.springframework.data.redis.core.RedisTemplate;
 15 import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
 16 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
 17 import org.springframework.data.redis.serializer.RedisSerializationContext;
 18 import org.springframework.data.redis.serializer.StringRedisSerializer;
 19 import redis.clients.jedis.JedisPoolConfig;
 20 
 21 import java.io.Serializable;
 22 import java.util.HashSet;
 23 import java.util.Set;
 24 
 25 @Configuration
 26 @Slf4j
 27 public class RedisConfig {
 28 
 29     @Value("${spring.redis.cluster.nodes}")
 30     private String host;
 31 //    @Value("${spring.redis.password}")
 32 //    private String password;
 33     @Value("${spring.redis.timeout}")
 34     private int connectionTimeout;
 35     @Value("${spring.redis.jedis.pool.max-active}")
 36     private int maxTotal;
 37     @Value("${spring.redis.jedis.pool.min-idle}")
 38     private int minIdle;
 39     @Value("${spring.redis.jedis.pool.max-idle}")
 40     private int maxIdle;
 41     @Value("${spring.redis.jedis.pool.max-wait}")
 42     private int maxWaitMillis;
 43 
 44     @Bean
 45     public RedisClusterConfiguration redisClusterConfiguration() {
 46         RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
 47         String[] hosts = host.split(",");
 48         Set<RedisNode> nodeList = new HashSet<RedisNode>();
 49         for (String hostAndPort : hosts) {
 50             String[] hostOrPort = hostAndPort.split(":");
 51             nodeList.add(new RedisNode(hostOrPort[0], Integer.parseInt(hostOrPort[1])));
 52         }
 53         redisClusterConfiguration.setClusterNodes(nodeList);
 54 //        redisClusterConfiguration.setMaxRedirects();
 55         return redisClusterConfiguration;
 56     }
 57 
 58     @Bean
 59     public JedisPoolConfig jedisPoolConfig() {
 60         JedisPoolConfig poolConfig = new JedisPoolConfig();
 61         poolConfig.setMaxIdle(this.maxIdle);
 62         poolConfig.setMinIdle(this.minIdle);
 63         poolConfig.setTestOnCreate(true);
 64         poolConfig.setTestOnBorrow(true);
 65         poolConfig.setTestOnReturn(true);
 66         poolConfig.setTestWhileIdle(true);
 67         return poolConfig;
 68     }
 69 
 70     @Bean("myJedisConnectionFactory")
 71     public JedisConnectionFactory jedisConnectionFactory(RedisClusterConfiguration redisClusterConfiguration,
 72                                                          JedisPoolConfig jedisPoolConfig) {
 73         JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(
 74                 redisClusterConfiguration, jedisPoolConfig);
 75 //        jedisConnectionFactory.setPassword(password);
 76         return jedisConnectionFactory;
 77     }
 78 
 79     @Bean
 80     RedisTemplate<String, Serializable> redisTemplate(@Qualifier("myJedisConnectionFactory")JedisConnectionFactory jedisConnectionFactory) {
 81         RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
 82         redisTemplate.setConnectionFactory(jedisConnectionFactory);
 83         Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
 84         // 设置值(value)的序列化采用Jackson2JsonRedisSerializer。
 85         redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
 86         // 设置键(key)的序列化采用StringRedisSerializer。
 87         redisTemplate.setKeySerializer(new StringRedisSerializer());
 88         redisTemplate.setHashKeySerializer(new StringRedisSerializer());
 89         redisTemplate.afterPropertiesSet();
 90         return redisTemplate;
 91     }
 92 
 93     @Bean
 94     public CacheManager cacheManager(@Qualifier("myJedisConnectionFactory")JedisConnectionFactory jedisConnectionFactory) {
 95         RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
 96         RedisCacheConfiguration redisCacheConfiguration = config
 97                 .serializeKeysWith(
 98                         RedisSerializationContext.SerializationPair
 99                                 .fromSerializer(new StringRedisSerializer()))
100                 .serializeValuesWith(
101                         RedisSerializationContext.SerializationPair
102                                 .fromSerializer(new GenericJackson2JsonRedisSerializer()));
103 
104         return RedisCacheManager.builder(jedisConnectionFactory)
105                 .cacheDefaults(redisCacheConfiguration).build();
106     }
107 }

 

4、RedisTemplate的使用

 1 package com.demo.redis.controller;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.data.redis.core.RedisTemplate;
 5 import org.springframework.web.bind.annotation.GetMapping;
 6 import org.springframework.web.bind.annotation.PathVariable;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RestController;
 9 
10 @RestController
11 @RequestMapping("/api/redis/")
12 public class RedisController {
13 
14     @Autowired
15     private RedisTemplate redisTemplate;
16 
17     //1- 字符串string
18     @GetMapping("/string/set/{key}/{value}")
19     public Object set(@PathVariable String key, @PathVariable String value){
20         redisTemplate.opsForValue().set(key,value);
21         return "success";
22     }
23 
24     @GetMapping("/string/get/{key}")
25     public Object get(@PathVariable String key){
26         return  redisTemplate.opsForValue().get(key);
27     }
28 
29 }

 

posted @ 2023-09-03 10:52  夏嘻嘻嘻嘻嘻  阅读(437)  评论(0编辑  收藏  举报