自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

SpringBoot 項目接入 Redis 集群

開發(fā) 項目管理 存儲軟件 Redis
Hello 大家好,我是鴨血粉絲,Redis 想必大家一定不會陌生,平常工作中或多或少都會用到,不管是用來存儲登錄信息還是用來緩存熱點數(shù)據(jù),對我們來說都是很有幫助的。

[[343353]]

本文轉(zhuǎn)載自微信公眾號「Java極客技術(shù)」,作者鴨血粉絲  。轉(zhuǎn)載本文請聯(lián)系Java極客技術(shù)公眾號。 

Hello 大家好,我是鴨血粉絲,Redis 想必大家一定不會陌生,平常工作中或多或少都會用到,不管是用來存儲登錄信息還是用來緩存熱點數(shù)據(jù),對我們來說都是很有幫助的。但是 Redis 的集群估計并不是每個人都會用到,因為很多業(yè)務(wù)場景或者系統(tǒng)都是一些簡單的管理系統(tǒng),并不會需要用到 Redis 的集群環(huán)境。

阿粉之前也是這樣,項目中用的的 Redis 是個單機環(huán)境,但是最近隨著終端量的上升,慢慢的發(fā)現(xiàn)單機已經(jīng)快支撐不住的,所以思考再三決定將 Redis 的環(huán)境升級成集群。下面阿粉給大家介紹一下在升級的過程中項目中需要調(diào)整的地方,這篇文章不涉及集群的搭建和配置,感興趣的同學自行搜索。

配置參數(shù)

因為這篇文章不介紹 Redis 集群的搭建,這里我們假設(shè)已經(jīng)有了一個 Redis 的集群環(huán)境,我們項目中需要調(diào)整以下幾個部分

  1. 修改配置參數(shù),集群的節(jié)點和密碼配置;
  2. 確保引入的 Jedis 版本支持設(shè)置密碼,spring-data-redis 1.8 以上,SpringBoot 1.5 以上才支持設(shè)置密碼;
  3. 注入 RedisTemplate;
  4. 編寫工具類;

修改配置參數(shù)

  1. ############### Redis 集群配置 ######################### 
  2. spring.custome.redis.cluster.nodes=172.20.0.1:7001,172.20.0.2:7002,172.20.0.3:7003 
  3. spring.custome.redis.cluster.max-redirects=3 
  4. spring.custome.redis.cluster.max-active=500 
  5. spring.custome.redis.cluster.max-wait=-1 
  6. spring.custome.redis.cluster.max-idle=500 
  7. spring.custome.redis.cluster.min-idle=20 
  8. spring.custome.redis.cluster.timeout=3000 
  9. spring.custome.redis.cluster.password=redis.cluster.password 

引入依賴(如果需要)

確保 SpringBoot 的版本大于 1.4.x 如果不是的話,采用如下配置,先排除 SpringBoot 中舊版本 Jedis 和 spring-data-redis,再依賴高版本的 Jedis 和 spring-data-redis。

  1. <dependency> 
  2.             <groupId>org.springframework.boot</groupId> 
  3.             <artifactId>spring-boot-starter-data-redis</artifactId> 
  4.             <!-- 1.4 版本 SpringBoot 中 Jedis 不支持密碼登錄 --> 
  5.             <exclusions> 
  6.                 <exclusion> 
  7.                     <groupId>redis.clients</groupId> 
  8.                     <artifactId>jedis</artifactId> 
  9.                 </exclusion> 
  10.                 <exclusion> 
  11.                     <groupId>org.springframework.data</groupId> 
  12.                     <artifactId>spring-data-redis</artifactId> 
  13.                 </exclusion> 
  14.             </exclusions> 
  15.         </dependency> 
  16.         <!-- 手動依賴 Jedis 和 spring-data-redis--> 
  17.         <dependency> 
  18.             <groupId>redis.clients</groupId> 
  19.             <artifactId>jedis</artifactId> 
  20.             <version>2.9.0</version> 
  21.         </dependency> 
  22.         <dependency> 
  23.             <groupId>org.springframework.data</groupId> 
  24.             <artifactId>spring-data-redis</artifactId> 
  25.             <version>1.8.0.RELEASE</version> 
  26.         </dependency> 

 

注入 RedisTemplate

注入 RedisTemplate 我們需要三個組件,分別是JedisConnectionFactory 、RedisClusterConfiguration、JedisPoolConfig,下面是注入RedisTempalte 的代碼。先根據(jù)配置創(chuàng)建 JedisConnectFactory 同時需要配置 RedisClusterConfiguration、JedisPoolConfig,最后將JedisConnectionFactory 返回用于創(chuàng)建RedisTemplate

  1. import com.fasterxml.jackson.annotation.JsonAutoDetect; 
  2. import com.fasterxml.jackson.annotation.PropertyAccessor; 
  3. import com.fasterxml.jackson.databind.ObjectMapper; 
  4. import org.apache.commons.pool2.impl.GenericObjectPoolConfig; 
  5. import org.springframework.beans.factory.annotation.Value; 
  6. import org.springframework.context.annotation.Bean; 
  7. import org.springframework.context.annotation.Primary
  8. import org.springframework.data.redis.connection.RedisClusterConfiguration; 
  9. import org.springframework.data.redis.connection.RedisNode; 
  10. import org.springframework.data.redis.connection.jedis.JedisClientConfiguration; 
  11. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; 
  12. import org.springframework.data.redis.core.RedisTemplate; 
  13. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 
  14. import org.springframework.data.redis.serializer.StringRedisSerializer; 
  15.  
  16. import java.time.Duration; 
  17. import java.util.ArrayList; 
  18. import java.util.List; 
  19.  
  20. public class RedisClusterConfig { 
  21.  
  22.     @Bean(name = "redisTemplate"
  23.     @Primary 
  24.     public RedisTemplate redisClusterTemplate(@Value("${spring.custome.redis.cluster.nodes}") String host, 
  25.                                      @Value("${spring.custome.redis.cluster.password}") String password
  26.                                      @Value("${spring.custome.redis.cluster.timeout}") long timeout, 
  27.                                      @Value("${spring.custome.redis.cluster.max-redirects}"int maxRedirect, 
  28.                                      @Value("${spring.custome.redis.cluster.max-active}"int maxActive, 
  29.                                      @Value("${spring.custome.redis.cluster.max-wait}"int maxWait, 
  30.                                      @Value("${spring.custome.redis.cluster.max-idle}"int maxIdle, 
  31.                                      @Value("${spring.custome.redis.cluster.min-idle}"int minIdle) { 
  32.  
  33.         JedisConnectionFactory connectionFactory =  jedisClusterConnectionFactory(host, password
  34.                 timeout, maxRedirect, maxActive, maxWait, maxIdle, minIdle); 
  35.         return createRedisClusterTemplate(connectionFactory); 
  36.     } 
  37.  
  38.     private JedisConnectionFactory jedisClusterConnectionFactory(String host, String password
  39.                                                                    long timeout, int maxRedirect, int maxActive, int maxWait, int maxIdle, int minIdle) { 
  40.         RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(); 
  41.         List<RedisNode> nodeList = new ArrayList<>(); 
  42.         String[] cNodes = host.split(","); 
  43.         //分割出集群節(jié)點 
  44.         for (String node : cNodes) { 
  45.             String[] hp = node.split(":"); 
  46.             nodeList.add(new RedisNode(hp[0], Integer.parseInt(hp[1]))); 
  47.         } 
  48.         redisClusterConfiguration.setClusterNodes(nodeList); 
  49.         redisClusterConfiguration.setPassword(password); 
  50.         redisClusterConfiguration.setMaxRedirects(maxRedirect); 
  51.  
  52.         // 連接池通用配置 
  53.         GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig(); 
  54.         genericObjectPoolConfig.setMaxIdle(maxIdle); 
  55.         genericObjectPoolConfig.setMaxTotal(maxActive); 
  56.         genericObjectPoolConfig.setMinIdle(minIdle); 
  57.         genericObjectPoolConfig.setMaxWaitMillis(maxWait); 
  58.         genericObjectPoolConfig.setTestWhileIdle(true); 
  59.         genericObjectPoolConfig.setTimeBetweenEvictionRunsMillis(300000); 
  60.  
  61.         JedisClientConfiguration.DefaultJedisClientConfigurationBuilder builder = (JedisClientConfiguration.DefaultJedisClientConfigurationBuilder) JedisClientConfiguration 
  62.                 .builder(); 
  63.         builder.connectTimeout(Duration.ofSeconds(timeout)); 
  64.         builder.usePooling(); 
  65.         builder.poolConfig(genericObjectPoolConfig); 
  66.         JedisConnectionFactory connectionFactory = new JedisConnectionFactory(redisClusterConfiguration, builder.build()); 
  67.         // 連接池初始化 
  68.         connectionFactory.afterPropertiesSet(); 
  69.  
  70.         return connectionFactory; 
  71.     } 
  72.  
  73.     private RedisTemplate createRedisClusterTemplate(JedisConnectionFactory redisConnectionFactory) { 
  74.         RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); 
  75.         redisTemplate.setConnectionFactory(redisConnectionFactory); 
  76.  
  77.         Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); 
  78.         ObjectMapper om = new ObjectMapper(); 
  79.         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 
  80.         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 
  81.         jackson2JsonRedisSerializer.setObjectMapper(om); 
  82.  
  83.         StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); 
  84.         // key采用String的序列化方式 
  85.         redisTemplate.setKeySerializer(stringRedisSerializer); 
  86.         // hash的key也采用String的序列化方式 
  87.         redisTemplate.setHashKeySerializer(stringRedisSerializer); 
  88.         // value序列化方式采用jackson 
  89.         redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); 
  90.         // hash的value序列化方式采用jackson 
  91.         redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); 
  92.         redisTemplate.afterPropertiesSet(); 
  93.  
  94.         return redisTemplate; 
  95.     } 

編寫工具類

其實到這里基本上已經(jīng)完成了,我們可以看到 SpringBoot 項目接入 Redis 集群還是比較簡單的,而且如果之前單機環(huán)境就是采用RedisTemplate 的話,現(xiàn)在也就不需要編寫工具類,之前的操作依舊有效。不過作為貼心的阿粉,我還是給大家準備了一個工具類,代碼太長,我只貼部分,需要完成代碼的可以到公眾號回復【源碼倉庫】獲取。

  1. /** 
  2.      *  刪除KEY 
  3.      * @param key 
  4.      * @return 
  5.      */ 
  6.     public boolean delete(String key) { 
  7.         try { 
  8.             return getTemplate().delete(key); 
  9.         } catch (Exception e) { 
  10.             log.error("redis hasKey() is error"); 
  11.             return false
  12.         } 
  13.     } 
  14.  
  15.     /** 
  16.      * 普通緩存獲取 
  17.      * 
  18.      * @param key 鍵 
  19.      * @return 值 
  20.      */ 
  21.     public Object get(String key) { 
  22.  
  23.         return key == null ? null : getTemplate().opsForValue().get(key); 
  24.     } 
  25.  
  26.     /** 
  27.      * 普通緩存放入 
  28.      * 
  29.      * @param key   鍵 
  30.      * @param value 值 
  31.      * @return true成功 false失敗 
  32.      */ 
  33.     public boolean set(String key, Object value) { 
  34.  
  35.         try { 
  36.             getTemplate().opsForValue().set(key, value); 
  37.             return true
  38.         } catch (Exception e) { 
  39.             log.error("redis set() is error"); 
  40.             return false
  41.         } 
  42.  
  43.     } 
  44.  
  45.     /** 
  46.      * 普通緩存放入并設(shè)置時間 
  47.      * 
  48.      * @param key   鍵 
  49.      * @param value 值 
  50.      * @param time  時間(秒) time要大于0 如果time小于等于0 將設(shè)置無限期 
  51.      * @return true成功 false 失敗 
  52.      */ 
  53.     public boolean set(String key, Object value, long time) { 
  54.         try { 
  55.             if (time > 0) { 
  56.                 getTemplate().opsForValue().set(key, value, time, TimeUnit.SECONDS); 
  57.             } else { 
  58.                 set(key, value); 
  59.             } 
  60.             return true
  61.         } catch (Exception e) { 
  62.             log.error("redis set() is error"); 
  63.             return false
  64.         } 
  65.     } 
  66.  
  67.     /** 
  68.      * 計數(shù)器 
  69.      * 
  70.      * @param key 鍵 
  71.      * @return 值 
  72.      */ 
  73.     public Long incr(String key) { 
  74.  
  75.         return getTemplate().opsForValue().increment(key); 
  76.     } 
  77.  
  78.     public Long incrBy(String key, long step) { 
  79.  
  80.         return getTemplate().opsForValue().increment(key, step); 
  81.     } 
  82.  
  83.     /** 
  84.      * HashGet 
  85.      * 
  86.      * @param key  鍵 不能為null 
  87.      * @param item 項 不能為null 
  88.      * @return 值 
  89.      */ 
  90.     public Object hget(String key, String item) { 
  91.  
  92.         return getTemplate().opsForHash().get(key, item); 
  93.     } 
  94.  
  95.     /** 
  96.      * 獲取hashKey對應(yīng)的所有鍵值 
  97.      * 
  98.      * @param key 鍵 
  99.      * @return 對應(yīng)的多個鍵值 
  100.      */ 
  101.     public Map<Object, Object> hmget(String key) { 
  102.  
  103.         return getTemplate().opsForHash().entries(key); 
  104.     } 
  105.  
  106.     /** 
  107.      * 獲取hashKey對應(yīng)的批量鍵值 
  108.      * @param key 
  109.      * @param values 
  110.      * @return 
  111.      */ 
  112.     public List<Object> hmget(String key, List<String> values) { 
  113.  
  114.         return getTemplate().opsForHash().multiGet(keyvalues); 
  115.     } 

上面隨機列了幾個方法,更多方案等待你的探索。

 

 

 

總結(jié)

今天阿粉給大家介紹了一下 SpringBoot 項目如何接入 Redis 集群,需要的朋友可以參考一下,不過阿粉還是要說一下,系統(tǒng)的設(shè)計不能過于冗余,如果短期內(nèi)還能支撐業(yè)務(wù)的發(fā)展,那就暫時不要考慮太復雜,畢竟系統(tǒng)的架構(gòu)是需要不斷的完善的,不可能剛開始的時候就設(shè)計出一套很完善的系統(tǒng)框架。隨著業(yè)務(wù)的不斷發(fā)展,當真正發(fā)現(xiàn)單機Redis 已經(jīng)無法滿足業(yè)務(wù)需求的時候再接入也不遲!

 

責任編輯:武曉燕 來源: Java極客技術(shù)
相關(guān)推薦

2021-03-23 08:39:27

SpringBootRedis管道技術(shù)

2025-04-25 09:30:41

RancherKubernetes集群

2024-11-04 15:49:43

Redis?數(shù)據(jù)遷移

2021-01-07 10:18:03

Redis數(shù)據(jù)庫環(huán)境搭建

2024-03-07 16:03:56

RedisDocker

2023-09-27 06:26:07

2023-09-26 01:07:34

2022-02-02 21:58:43

Redis集群Undermoon

2019-10-23 09:20:11

Redis集群主從復制

2025-04-29 01:30:00

Redis集群節(jié)點

2021-08-09 06:27:04

Gulp項目工具

2025-02-24 10:07:09

Redis節(jié)點遷移集群

2021-07-11 07:05:28

RedisSpringBoot用法

2022-02-09 15:36:49

Redis主從模式哨兵模式

2021-10-07 20:36:45

Redis集群場景

2024-09-11 20:05:56

2020-01-10 15:42:13

SpringBootRedis數(shù)據(jù)庫

2019-09-16 16:05:13

Redis集群模式

2022-01-26 20:43:04

集群構(gòu)建塊Chunk

2022-05-31 08:04:03

Redis高可用集群
點贊
收藏

51CTO技術(shù)棧公眾號