打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
spring boot实际应用(五) redis
redis是一个目前非常流行的缓存数据库,具体技术细节这里就不做描述了,下面说下干货,怎么实际应用

目前项目都使用spring boot来实现了,SO 我也来点新鲜的,说实话确实好使。

先说下使用的依赖
  1. <dependencies>  
  2.      <dependency>  
  3.            <groupId>org.springframework.boot</groupId>  
  4.           <artifactId>spring-boot-starter-data-redis</artifactId>  
  5.      </dependency>  
  6.      <dependency>  
  7.            <groupId>com.alibaba</groupId>  
  8.            <artifactId>fastjson</artifactId>  
  9.      </dependency>  
  10.      <dependency>  
  11.            <groupId>org.springframework.boot</groupId>  
  12.           <artifactId>spring-boot-configuration-processor</artifactId>  
  13.            <optional>true</optional>  
  14.      </dependency>  
  15.   </dependencies>  



1、基本配置,这个不管用配置文件还是config都少不了的,在这里我学习了spring boot的特性,。就是做了个底层包,在公司项目只要加载了这个包就默认启动redis。
目前redis 有sentinel cluster两种模式,下面贴代码

sentinel配置类

  1. package com.ecej.nove.redis.config;  
  2.   
  3. import java.util.HashSet;  
  4.   
  5. import javax.annotation.Resource;  
  6.   
  7. import org.slf4j.Logger;  
  8. import org.slf4j.LoggerFactory;  
  9. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;  
  10. import org.springframework.boot.context.properties.EnableConfigurationProperties;  
  11. import org.springframework.context.annotation.Bean;  
  12. import org.springframework.context.annotation.Configuration;  
  13. import org.springframework.data.redis.connection.RedisSentinelConfiguration;  
  14. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;  
  15. import org.springframework.data.redis.core.RedisTemplate;  
  16. import org.springframework.data.redis.serializer.StringRedisSerializer;  
  17. import org.springframework.util.StringUtils;  
  18.   
  19. import redis.clients.jedis.JedisPoolConfig;  
  20.   
  21. /** 
  22.  *  
  23.  * @author QIANG 
  24.  * 
  25.  */  
  26. @Configuration  
  27. @EnableConfigurationProperties(EcejRedisProperties.class)  
  28. @ConditionalOnProperty(name = "ecej.redis.sentinel")  
  29. public class RedisSentinelConfig {  
  30.     private Logger LOG = LoggerFactory.getLogger(RedisSentinelConfig.class);  
  31.   
  32.     @Resource  
  33.     private EcejRedisProperties redisProperties;  
  34.   
  35.     public JedisPoolConfig jedisPoolConfig() {  
  36.         JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();  
  37.         jedisPoolConfig.setMaxIdle(redisProperties.getMaxIdle());  
  38.         jedisPoolConfig.setMaxTotal(redisProperties.getMaxTotal());  
  39.         jedisPoolConfig.setMaxWaitMillis(redisProperties.getMaxWaitMillis());  
  40.         return jedisPoolConfig;  
  41.   
  42.     }  
  43.   
  44.     public RedisSentinelConfiguration jedisSentinelConfig() {  
  45.         String[] hosts = redisProperties.getHostName().split(",");  
  46.         HashSet<String> sentinelHostAndPorts = new HashSet<>();  
  47.         for (String hn : hosts) {  
  48.             sentinelHostAndPorts.add(hn);  
  49.         }  
  50.         return new RedisSentinelConfiguration(redisProperties.getMastername(), sentinelHostAndPorts);  
  51.   
  52.     }  
  53.   
  54.     @Bean  
  55.     public JedisConnectionFactory jedisConnectionFactory() {  
  56.   
  57.         JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(jedisSentinelConfig(),  
  58.                 jedisPoolConfig());  
  59.         if (!StringUtils.isEmpty(redisProperties.getPassword()))  
  60.             jedisConnectionFactory.setPassword(redisProperties.getPassword());  
  61.         return jedisConnectionFactory;  
  62.     }  
  63.   
  64.     @Bean  
  65.     public RedisTemplate<String, String> redisTemplate() {  
  66.   
  67.         RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();  
  68.         redisTemplate.setConnectionFactory(jedisConnectionFactory());  
  69.         redisTemplate.setDefaultSerializer(new StringRedisSerializer());  
  70.         LOG.info("create redisTemplate success");  
  71.         return redisTemplate;  
  72.     }  
  73.   
  74. }  


下面贴出cluster配置

  1. package com.ecej.nove.redis.config;  
  2.   
  3. import java.util.HashSet;  
  4. import java.util.Set;  
  5.   
  6. import javax.annotation.Resource;  
  7.   
  8. import org.slf4j.Logger;  
  9. import org.slf4j.LoggerFactory;  
  10. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;  
  11. import org.springframework.boot.context.properties.EnableConfigurationProperties;  
  12. import org.springframework.context.annotation.Bean;  
  13. import org.springframework.context.annotation.Configuration;  
  14. import org.springframework.data.redis.connection.RedisClusterConfiguration;  
  15. import org.springframework.data.redis.connection.RedisClusterNode;  
  16. import org.springframework.data.redis.connection.RedisNode;  
  17. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;  
  18. import org.springframework.data.redis.core.RedisTemplate;  
  19. import org.springframework.data.redis.serializer.StringRedisSerializer;  
  20. import org.springframework.util.StringUtils;  
  21.   
  22. import redis.clients.jedis.JedisPoolConfig;  
  23.   
  24. /** 
  25.  *  
  26.  * @author QIANG 
  27.  * 
  28.  */  
  29. @Configuration  
  30. @EnableConfigurationProperties(EcejRedisProperties.class)  
  31. @ConditionalOnProperty(name = "ecej.redis.cluster")  
  32. public class RedisClusterConfig {  
  33.     private Logger LOG = LoggerFactory.getLogger(RedisClusterConfig.class);  
  34.   
  35.     @Resource  
  36.     private EcejRedisProperties redisProperties;  
  37.   
  38.     public JedisPoolConfig jedisPoolConfig() {  
  39.   
  40.         JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();  
  41.         jedisPoolConfig.setMaxIdle(redisProperties.getMaxIdle());  
  42.         jedisPoolConfig.setMaxTotal(redisProperties.getMaxTotal());  
  43.         jedisPoolConfig.setMaxWaitMillis(redisProperties.getMaxWaitMillis());  
  44.         return jedisPoolConfig;  
  45.   
  46.     }  
  47.   
  48.     public RedisClusterConfiguration redisClusterConfiguration() {  
  49.   
  50.         RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();  
  51.         String[] hosts = redisProperties.getHostName().split(":");  
  52.         Set<RedisNode> redisNodes = new HashSet<>();  
  53.         redisNodes.add(new RedisClusterNode(hosts[0], Integer.valueOf(hosts[1])));  
  54.         redisClusterConfiguration.setClusterNodes(redisNodes);  
  55.         redisClusterConfiguration.setMaxRedirects(redisProperties.getMaxRedirects());  
  56.         return redisClusterConfiguration;  
  57.   
  58.     }  
  59.   
  60.     @Bean  
  61.     public JedisConnectionFactory jedisConnectionFactory() {  
  62.         JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisClusterConfiguration(),  
  63.                 jedisPoolConfig());  
  64.         if (!StringUtils.isEmpty(redisProperties.getPassword()))  
  65.             jedisConnectionFactory.setPassword(redisProperties.getPassword());  
  66.         return jedisConnectionFactory;  
  67.     }  
  68.   
  69.     @Bean  
  70.     public RedisTemplate<String, String> redisTemplate() {  
  71.   
  72.         RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();  
  73.         redisTemplate.setConnectionFactory(jedisConnectionFactory());  
  74.         redisTemplate.setDefaultSerializer(new StringRedisSerializer());  
  75.         LOG.info("create RedisTemplate success");  
  76.         return redisTemplate;  
  77.     }  
  78. }  
  79.   
  80.   
  81. 使用的配置类,用于加载参数  
  82.   
  83. package com.ecej.nove.redis.config;  
  84.   
  85. import org.springframework.boot.context.properties.ConfigurationProperties;  
  86.   
  87. /** 
  88.  * 
  89.  * @author QIANG 
  90.  * 
  91.  */  
  92. @ConfigurationProperties(prefix = "ecej.redis")  
  93. public class EcejRedisProperties {  
  94.   
  95.      /** 
  96.       * Max number of "idle" connections in the pool. Use a negative value to 
  97.       * indicate an unlimited number of idle connections. 
  98.       */  
  99.      private int maxIdle = 10;  
  100.   
  101.      /** 
  102.       * 最大连接数 
  103.       */  
  104.      private int maxTotal = 500;  
  105.   
  106.      private int maxWaitMillis = 3000;  
  107.   
  108.      private String hostName = "localhost";  
  109.   
  110.      private String password;  
  111.   
  112.      /** 
  113.       * Maximum number of redirects to follow when executing commands across the 
  114.       * cluster. 
  115.       */  
  116.      private int maxRedirects = 10;  
  117.   
  118.      private String mastername;  
  119.   
  120.      public int getMaxIdle() {  
  121.            return maxIdle;  
  122.      }  
  123.   
  124.      public void setMaxIdle(int maxIdle) {  
  125.            this.maxIdle = maxIdle;  
  126.      }  
  127.   
  128.      public int getMaxTotal() {  
  129.            return maxTotal;  
  130.      }  
  131.   
  132.      public void setMaxTotal(int maxTotal) {  
  133.            this.maxTotal = maxTotal;  
  134.      }  
  135.   
  136.      public int getMaxWaitMillis() {  
  137.            return maxWaitMillis;  
  138.      }  
  139.   
  140.      public void setMaxWaitMillis(int maxWaitMillis) {  
  141.            this.maxWaitMillis = maxWaitMillis;  
  142.      }  
  143.   
  144.      public String getHostName() {  
  145.            return hostName;  
  146.      }  
  147.   
  148.      public void setHostName(String hostName) {  
  149.            this.hostName = hostName;  
  150.      }  
  151.   
  152.      public String getPassword() {  
  153.            return password;  
  154.      }  
  155.   
  156.      public void setPassword(String password) {  
  157.            this.password = password;  
  158.      }  
  159.   
  160.      public int getMaxRedirects() {  
  161.            return maxRedirects;  
  162.      }  
  163.   
  164.      public void setMaxRedirects(int maxRedirects) {  
  165.            this.maxRedirects = maxRedirects;  
  166.      }  
  167.   
  168.      public String getMastername() {  
  169.            return mastername;  
  170.      }  
  171.   
  172.      public void setMastername(String mastername) {  
  173.            this.mastername = mastername;  
  174.      }  
  175.   
  176. }  


怎么使用呢,下面编写了使用的快捷方法

  1. package com.ecej.nove.redis.utils;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import java.util.Set;  
  7. import java.util.concurrent.TimeUnit;  
  8.   
  9. import javax.annotation.PostConstruct;  
  10. import javax.annotation.Resource;  
  11.   
  12. import org.springframework.data.redis.connection.RedisZSetCommands.Tuple;  
  13. import org.springframework.data.redis.core.ListOperations;  
  14. import org.springframework.data.redis.core.RedisCallback;  
  15. import org.springframework.data.redis.core.RedisTemplate;  
  16. import org.springframework.data.redis.core.SetOperations;  
  17. import org.springframework.data.redis.core.ValueOperations;  
  18.   
  19. import com.alibaba.fastjson.JSON;  
  20. import com.alibaba.fastjson.parser.Feature;  
  21.   
  22. /** 
  23.  * 
  24.  * @author QIANG 
  25.  * 
  26.  */  
  27. public class JedisClusterUtils {  
  28.   
  29.     @Resource  
  30.     private RedisTemplate<String, String> redisTemplate;  
  31.   
  32.     private static JedisClusterUtils cacheUtils;  
  33.   
  34.     @PostConstruct  
  35.     public void init() {  
  36.         cacheUtils = this;  
  37.         cacheUtils.redisTemplate = this.redisTemplate;  
  38.     }  
  39.   
  40.     /** 
  41.      * 将数据存入缓存 
  42.      * 
  43.      * @param key 
  44.      * @param val 
  45.      * @return 
  46.      */  
  47.     public static void saveString(String key, String val) {  
  48.   
  49.         ValueOperations<String, String> vo = cacheUtils.redisTemplate.opsForValue();  
  50.         vo.set(key, val);  
  51.     }  
  52.   
  53.     /** 
  54.      * 将数据存入缓存的集合中 
  55.      * 
  56.      * @param key 
  57.      * @param val 
  58.      * @return 
  59.      */  
  60.     public static void saveToSet(String key, String val) {  
  61.   
  62.         SetOperations<String, String> so = cacheUtils.redisTemplate.opsForSet();  
  63.   
  64.         so.add(key, val);  
  65.     }  
  66.   
  67.     /** 
  68.      * 
  69.      * 
  70.      * @param key 
  71.      *            缓存Key 
  72.      * @return keyValue 
  73.      * @author:mijp 
  74.      * @since:2017/1/16 13:23 
  75.      */  
  76.     public static String getFromSet(String key) {  
  77.         return cacheUtils.redisTemplate.opsForSet().pop(key);  
  78.     }  
  79.   
  80.     /** 
  81.      * 将 key的值保存为 value ,当且仅当 key 不存在。 若给定的 key 已经存在,则 SETNX 不做任何动作。 SETNX 是『SET 
  82.      * if Not eXists』(如果不存在,则 SET)的简写。 <br> 
  83.      * 保存成功,返回 true <br> 
  84.      * 保存失败,返回 false 
  85.      */  
  86.     public static boolean saveNX(String key, String val) {  
  87.   
  88.         /** 设置成功,返回 1 设置失败,返回 0 **/  
  89.         return cacheUtils.redisTemplate.execute((RedisCallback<Boolean>) connection -> {  
  90.             return connection.setNX(key.getBytes(), val.getBytes());  
  91.         });  
  92.   
  93.     }  
  94.   
  95.     /** 
  96.      * 将 key的值保存为 value ,当且仅当 key 不存在。 若给定的 key 已经存在,则 SETNX 不做任何动作。 SETNX 是『SET 
  97.      * if Not eXists』(如果不存在,则 SET)的简写。 <br> 
  98.      * 保存成功,返回 true <br> 
  99.      * 保存失败,返回 false 
  100.      * 
  101.      * @param key 
  102.      * @param val 
  103.      * @param expire 
  104.      *            超时时间 
  105.      * @return 保存成功,返回 true 否则返回 false 
  106.      */  
  107.     public static boolean saveNX(String key, String val, int expire) {  
  108.   
  109.         boolean ret = saveNX(key, val);  
  110.         if (ret) {  
  111.             cacheUtils.redisTemplate.expire(key, expire, TimeUnit.SECONDS);  
  112.         }  
  113.         return ret;  
  114.     }  
  115.   
  116.     /** 
  117.      * 将数据存入缓存(并设置失效时间) 
  118.      * 
  119.      * @param key 
  120.      * @param val 
  121.      * @param seconds 
  122.      * @return 
  123.      */  
  124.     public static void saveString(String key, String val, int seconds) {  
  125.   
  126.         cacheUtils.redisTemplate.opsForValue().set(key, val, seconds, TimeUnit.SECONDS);  
  127.     }  
  128.   
  129.     /** 
  130.      * 将自增变量存入缓存 
  131.      */  
  132.     public static void saveSeq(String key, long seqNo) {  
  133.   
  134.         cacheUtils.redisTemplate.delete(key);  
  135.         cacheUtils.redisTemplate.opsForValue().increment(key, seqNo);  
  136.     }  
  137.   
  138.     /** 
  139.      * 将递增浮点数存入缓存 
  140.      */  
  141.     public static void saveFloat(String key, float data) {  
  142.   
  143.         cacheUtils.redisTemplate.delete(key);  
  144.         cacheUtils.redisTemplate.opsForValue().increment(key, data);  
  145.     }  
  146.   
  147.     /** 
  148.      * 保存复杂类型数据到缓存 
  149.      * 
  150.      * @param key 
  151.      * @param obj 
  152.      * @return 
  153.      */  
  154.     public static void saveBean(String key, Object obj) {  
  155.   
  156.         cacheUtils.redisTemplate.opsForValue().set(key, JSON.toJSONString(obj));  
  157.     }  
  158.   
  159.     /** 
  160.      * 保存复杂类型数据到缓存(并设置失效时间) 
  161.      * 
  162.      * @param key 
  163.      * @param Object 
  164.      * @param seconds 
  165.      * @return 
  166.      */  
  167.     public static void saveBean(String key, Object obj, int seconds) {  
  168.   
  169.         cacheUtils.redisTemplate.opsForValue().set(key, JSON.toJSONString(obj), seconds, TimeUnit.SECONDS);  
  170.     }  
  171.   
  172.     /** 
  173.      * 功能: 存到指定的队列中<br /> 
  174.      * 左近右出<br\> 作者: 耿建委 
  175.      * 
  176.      * @param key 
  177.      * @param val 
  178.      * @param size 
  179.      *            队列大小限制 0:不限制 
  180.      */  
  181.     public static void saveToQueue(String key, String val, long size) {  
  182.   
  183.         ListOperations<String, String> lo = cacheUtils.redisTemplate.opsForList();  
  184.   
  185.         if (size > 0 && lo.size(key) >= size) {  
  186.             lo.rightPop(key);  
  187.         }  
  188.         lo.leftPush(key, val);  
  189.     }  
  190.   
  191.     /** 
  192.      * 保存到hash集合中 
  193.      * 
  194.      * @param hName 
  195.      *            集合名 
  196.      * @param key 
  197.      * @param val 
  198.      */  
  199.     public static void hashSet(String hName, String key, String value) {  
  200.   
  201.         cacheUtils.redisTemplate.opsForHash().put(hName, key, value);  
  202.     }  
  203.   
  204.     /** 
  205.      * 根据key获取所以值 
  206.      *  
  207.      * @param key 
  208.      * @return 
  209.      */  
  210.     public static Map<Object, Object> hgetAll(String key) {  
  211.   
  212.         return cacheUtils.redisTemplate.opsForHash().entries(key);  
  213.     }  
  214.   
  215.     /** 
  216.      * 保存到hash集合中 
  217.      * 
  218.      * @param <T> 
  219.      * 
  220.      * @param hName 
  221.      *            集合名 
  222.      * @param key 
  223.      * @param val 
  224.      */  
  225.     public static <T> void hashSet(String hName, String key, T t) {  
  226.   
  227.         hashSet(hName, key, JSON.toJSONString(t));  
  228.     }  
  229.   
  230.     /** 
  231.      * 取得复杂类型数据 
  232.      * 
  233.      * @param key 
  234.      * @param obj 
  235.      * @param clazz 
  236.      * @return 
  237.      */  
  238.     public static <T> T getBean(String key, Class<T> clazz) {  
  239.   
  240.         String value = cacheUtils.redisTemplate.opsForValue().get(key);  
  241.         if (value == null) {  
  242.             return null;  
  243.         }  
  244.         return JSON.parseObject(value, clazz);  
  245.     }  
  246.   
  247.     /** 
  248.      * 从缓存中取得字符串数据 
  249.      * 
  250.      * @param key 
  251.      * @return 数据 
  252.      */  
  253.     public static String getString(String key) {  
  254.         cacheUtils.redisTemplate.opsForValue().get(key);  
  255.   
  256.         return cacheUtils.redisTemplate.opsForValue().get(key);  
  257.     }  
  258.   
  259.     /** 
  260.      * 
  261.      * 功能: 从指定队列里取得数据<br /> 
  262.      * 作者: 耿建委 
  263.      * 
  264.      * @param key 
  265.      * @param size 
  266.      *            数据长度 
  267.      * @return 
  268.      */  
  269.     public static List<String> getFromQueue(String key, long size) {  
  270.   
  271.         boolean flag = cacheUtils.redisTemplate.execute((RedisCallback<Boolean>) connection -> {  
  272.             return connection.exists(key.getBytes());  
  273.         });  
  274.   
  275.         if (flag) {  
  276.             return new ArrayList<>();  
  277.         }  
  278.         ListOperations<String, String> lo = cacheUtils.redisTemplate.opsForList();  
  279.         if (size > 0) {  
  280.             return lo.range(key, 0, size - 1);  
  281.         } else {  
  282.             return lo.range(key, 0, lo.size(key) - 1);  
  283.         }  
  284.     }  
  285.   
  286.     /** 
  287.      * 
  288.      * 功能: 从指定队列里取得数据<br /> 
  289.      * 作者: 耿建委 
  290.      * 
  291.      * @param key 
  292.      * @return 
  293.      */  
  294.     public static String popQueue(String key) {  
  295.   
  296.         return cacheUtils.redisTemplate.opsForList().rightPop(key);  
  297.   
  298.     }  
  299.   
  300.     /** 
  301.      * 取得序列值的下一个 
  302.      * 
  303.      * @param key 
  304.      * @return 
  305.      */  
  306.     public static Long getSeqNext(String key) {  
  307.   
  308.         return cacheUtils.redisTemplate.execute((RedisCallback<Long>) connection -> {  
  309.   
  310.             return connection.incr(key.getBytes());  
  311.   
  312.         });  
  313.     }  
  314.   
  315.     /** 
  316.      * 取得序列值的下一个 
  317.      * 
  318.      * @param key 
  319.      * @return 
  320.      */  
  321.     public static Long getSeqNext(String key, long value) {  
  322.   
  323.         return cacheUtils.redisTemplate.execute((RedisCallback<Long>) connection -> {  
  324.   
  325.             return connection.incrBy(key.getBytes(), value);  
  326.   
  327.         });  
  328.   
  329.     }  
  330.   
  331.     /** 
  332.      * 将序列值回退一个 
  333.      * 
  334.      * @param key 
  335.      * @return 
  336.      */  
  337.     public static void getSeqBack(String key) {  
  338.   
  339.         cacheUtils.redisTemplate.execute((RedisCallback<Long>) connection -> connection.decr(key.getBytes()));  
  340.   
  341.     }  
  342.   
  343.     /** 
  344.      * 从hash集合里取得 
  345.      * 
  346.      * @param hName 
  347.      * @param key 
  348.      * @return 
  349.      */  
  350.     public static Object hashGet(String hName, String key) {  
  351.   
  352.         return cacheUtils.redisTemplate.opsForHash().get(hName, key);  
  353.     }  
  354.   
  355.     public static <T> T hashGet(String hName, String key, Class<T> clazz) {  
  356.   
  357.         return JSON.parseObject((String) hashGet(hName, key), clazz);  
  358.     }  
  359.   
  360.     /** 
  361.      * 增加浮点数的值 
  362.      * 
  363.      * @param key 
  364.      * @return 
  365.      */  
  366.     public static Double incrFloat(String key, double incrBy) {  
  367.   
  368.         return cacheUtils.redisTemplate.execute((RedisCallback<Double>) connection -> {  
  369.   
  370.             return connection.incrBy(key.getBytes(), incrBy);  
  371.   
  372.         });  
  373.     }  
  374.   
  375.     /** 
  376.      * 判断是否缓存了数据 
  377.      * 
  378.      * @param key 
  379.      *            数据KEY 
  380.      * @return 判断是否缓存了 
  381.      */  
  382.     public static boolean isCached(String key) {  
  383.   
  384.         return cacheUtils.redisTemplate.execute((RedisCallback<Boolean>) connection -> {  
  385.             return connection.exists(key.getBytes());  
  386.         });  
  387.     }  
  388.   
  389.     /** 
  390.      * 判断hash集合中是否缓存了数据 
  391.      * 
  392.      * @param hName 
  393.      * @param key 
  394.      *            数据KEY 
  395.      * @return 判断是否缓存了 
  396.      */  
  397.     public static boolean hashCached(String hName, String key) {  
  398.   
  399.         return cacheUtils.redisTemplate.execute((RedisCallback<Boolean>) connection -> {  
  400.             return connection.hExists(key.getBytes(), key.getBytes());  
  401.         });  
  402.     }  
  403.   
  404.     /** 
  405.      * 判断是否缓存在指定的集合中 
  406.      * 
  407.      * @param key 
  408.      *            数据KEY 
  409.      * @param val 
  410.      *            数据 
  411.      * @return 判断是否缓存了 
  412.      */  
  413.     public static boolean isMember(String key, String val) {  
  414.   
  415.         return cacheUtils.redisTemplate.execute((RedisCallback<Boolean>) connection -> {  
  416.             return connection.sIsMember(key.getBytes(), val.getBytes());  
  417.         });  
  418.     }  
  419.   
  420.     /** 
  421.      * 从缓存中删除数据 
  422.      * 
  423.      * @param string 
  424.      * @return 
  425.      */  
  426.     public static void delKey(String key) {  
  427.   
  428.         cacheUtils.redisTemplate.execute((RedisCallback<Long>) connection -> connection.del(key.getBytes()));  
  429.     }  
  430.   
  431.     /** 
  432.      * 设置超时时间 
  433.      * 
  434.      * @param key 
  435.      * @param seconds 
  436.      */  
  437.     public static void expire(String key, int seconds) {  
  438.         cacheUtils.redisTemplate  
  439.                 .execute((RedisCallback<Boolean>) connection -> connection.expire(key.getBytes(), seconds));  
  440.   
  441.     }  
  442.   
  443.     /** 
  444.      * 列出set中所有成员 
  445.      * 
  446.      * @param setName 
  447.      *            set名 
  448.      * @return 
  449.      */  
  450.     public static Set<Object> listSet(String setName) {  
  451.   
  452.         return cacheUtils.redisTemplate.opsForHash().keys(setName);  
  453.   
  454.     }  
  455.   
  456.     /** 
  457.      * 向set中追加一个值 
  458.      * 
  459.      * @param setName 
  460.      *            set名 
  461.      * @param value 
  462.      */  
  463.     public static void setSave(String setName, String value) {  
  464.   
  465.         cacheUtils.redisTemplate  
  466.                 .execute((RedisCallback<Long>) connection -> connection.sAdd(setName.getBytes(), value.getBytes()));  
  467.   
  468.     }  
  469.   
  470.     /** 
  471.      * 逆序列出sorted set包括分数的set列表 
  472.      * 
  473.      * @param key 
  474.      *            set名 
  475.      * @param start 
  476.      *            开始位置 
  477.      * @param end 
  478.      *            结束位置 
  479.      * @return 列表 
  480.      */  
  481.     public static Set<Tuple> listSortedsetRev(String key, int start, int end) {  
  482.   
  483.         return cacheUtils.redisTemplate.execute((RedisCallback<Set<Tuple>>) connection -> {  
  484.             return connection.zRevRangeWithScores(key.getBytes(), start, end);  
  485.         });  
  486.     }  
  487.   
  488.     /** 
  489.      * 逆序取得sorted sort排名 
  490.      * 
  491.      * @param key 
  492.      *            set名 
  493.      * @param member 
  494.      *            成员名 
  495.      * @return 排名 
  496.      */  
  497.     public static Long getRankRev(String key, String member) {  
  498.   
  499.         return cacheUtils.redisTemplate.execute((RedisCallback<Long>) connection -> {  
  500.             return connection.zRevRank(key.getBytes(), member.getBytes());  
  501.         });  
  502.   
  503.     }  
  504.   
  505.     /** 
  506.      * 根据成员名取得sorted sort分数 
  507.      * 
  508.      * @param key 
  509.      *            set名 
  510.      * @param member 
  511.      *            成员名 
  512.      * @return 分数 
  513.      */  
  514.     public static Double getMemberScore(String key, String member) {  
  515.   
  516.         return cacheUtils.redisTemplate.execute((RedisCallback<Double>) connection -> {  
  517.             return connection.zScore(key.getBytes(), member.getBytes());  
  518.         });  
  519.     }  
  520.   
  521.     /** 
  522.      * 向sorted set中追加一个值 
  523.      * 
  524.      * @param key 
  525.      *            set名 
  526.      * @param score 
  527.      *            分数 
  528.      * @param member 
  529.      *            成员名称 
  530.      */  
  531.     public static void saveToSortedset(String key, Double score, String member) {  
  532.   
  533.         cacheUtils.redisTemplate.execute(  
  534.                 (RedisCallback<Boolean>) connection -> connection.zAdd(key.getBytes(), score, member.getBytes()));  
  535.     }  
  536.   
  537.     /** 
  538.      * 从sorted set删除一个值 
  539.      * 
  540.      * @param key 
  541.      *            set名 
  542.      * @param member 
  543.      *            成员名称 
  544.      */  
  545.     public static void delFromSortedset(String key, String member) {  
  546.         cacheUtils.redisTemplate  
  547.                 .execute((RedisCallback<Long>) connection -> connection.zRem(key.getBytes(), member.getBytes()));  
  548.   
  549.     }  
  550.   
  551.     /** 
  552.      * 从hash map中取得复杂类型数据 
  553.      * 
  554.      * @param key 
  555.      * @param field 
  556.      * @param clazz 
  557.      */  
  558.     public static <T> T getBeanFromMap(String key, String field, Class<T> clazz) {  
  559.   
  560.         byte[] input = cacheUtils.redisTemplate.execute((RedisCallback<byte[]>) connection -> {  
  561.             return connection.hGet(key.getBytes(), field.getBytes());  
  562.         });  
  563.         return JSON.parseObject(input, clazz, Feature.AutoCloseSource);  
  564.     }  
  565.   
  566.     /** 
  567.      * 从hashmap中删除一个值 
  568.      * 
  569.      * @param key 
  570.      *            map名 
  571.      * @param field 
  572.      *            成员名称 
  573.      */  
  574.     public static void delFromMap(String key, String field) {  
  575.   
  576.         cacheUtils.redisTemplate  
  577.                 .execute((RedisCallback<Long>) connection -> connection.hDel(key.getBytes(), field.getBytes()));  
  578.   
  579.     }  
  580.   
  581.     /** 
  582.      * 
  583.      * @Description: 根据key增长 ,计数器 
  584.      * @author clg 
  585.      * @date 2016年6月30日 下午2:37:52 
  586.      * 
  587.      * @param key 
  588.      * @return 
  589.      */  
  590.     public static long incr(String key) {  
  591.   
  592.         return cacheUtils.redisTemplate.execute((RedisCallback<Long>) connection -> {  
  593.             return connection.incr(key.getBytes());  
  594.         });  
  595.     }  
  596.   
  597.     /** 
  598.      * 
  599.      * @Description: 根据key获取当前计数结果 
  600.      * @author clg 
  601.      * @date 2016年6月30日 下午2:38:20 
  602.      * 
  603.      * @param key 
  604.      * @return 
  605.      */  
  606.     public static String getCount(String key) {  
  607.   
  608.         return cacheUtils.redisTemplate.opsForValue().get(key);  
  609.     }  
  610.   
  611.     /** 
  612.      * 将所有指定的值插入到存于 key 的列表的头部。如果 key 不存在,那么在进行 push 操作前会创建一个空列表 
  613.      * 
  614.      * @param <T> 
  615.      * 
  616.      * @param key 
  617.      * @param value 
  618.      * @return 
  619.      */  
  620.     public static <T> Long lpush(String key, T value) {  
  621.   
  622.         return cacheUtils.redisTemplate.opsForList().leftPush(key, JSON.toJSONString(value));  
  623.     }  
  624.   
  625.     /** 
  626.      * 只有当 key 已经存在并且存着一个 list 的时候,在这个 key 下面的 list 的头部插入 value。 与 LPUSH 相反,当 
  627.      * key 不存在的时候不会进行任何操作 
  628.      * 
  629.      * @param key 
  630.      * @param value 
  631.      * @return 
  632.      */  
  633.     public static <T> Long lpushx(String key, T value) {  
  634.   
  635.         return cacheUtils.redisTemplate.opsForList().leftPushIfPresent(key, JSON.toJSONString(value));  
  636.     }  
  637.   
  638.     /** 
  639.      * 返回存储在 key 里的list的长度。 如果 key 不存在,那么就被看作是空list,并且返回长度为 0 
  640.      * 
  641.      * @param key 
  642.      * @return 
  643.      */  
  644.     public static Long llen(String key) {  
  645.   
  646.         return cacheUtils.redisTemplate.opsForList().size(key);  
  647.     }  
  648.   
  649.     /** 
  650.      * 返回存储在 key 的列表里指定范围内的元素。 start 和 end 
  651.      * 偏移量都是基于0的下标,即list的第一个元素下标是0(list的表头),第二个元素下标是1,以此类推 
  652.      * 
  653.      * @param key 
  654.      * @return 
  655.      */  
  656.     public static List<String> lrange(String key, long start, long end) {  
  657.   
  658.         return cacheUtils.redisTemplate.opsForList().range(key, start, end);  
  659.     }  
  660.   
  661.     /** 
  662.      * 移除并且返回 key 对应的 list 的第一个元素 
  663.      * 
  664.      * @param key 
  665.      * @return 
  666.      */  
  667.     public static String lpop(String key) {  
  668.   
  669.         return cacheUtils.redisTemplate.opsForList().leftPop(key);  
  670.     }  
  671.   
  672.     /** 
  673.      * 保存到hash集合中 只在 key 指定的哈希集中不存在指定的字段时,设置字段的值。如果 key 指定的哈希集不存在,会创建一个新的哈希集并与 
  674.      * key 关联。如果字段已存在,该操作无效果。 
  675.      * 
  676.      * @param hName 
  677.      *            集合名 
  678.      * @param key 
  679.      * @param val 
  680.      */  
  681.     public static void hsetnx(String hName, String key, String value) {  
  682.   
  683.         cacheUtils.redisTemplate.execute((RedisCallback<Boolean>) connection -> connection.hSetNX(key.getBytes(),  
  684.                 key.getBytes(), value.getBytes()));  
  685.   
  686.     }  
  687.   
  688.     /** 
  689.      * 保存到hash集合中 只在 key 指定的哈希集中不存在指定的字段时,设置字段的值。如果 key 指定的哈希集不存在,会创建一个新的哈希集并与 
  690.      * key 关联。如果字段已存在,该操作无效果。 
  691.      * 
  692.      * @param <T> 
  693.      * 
  694.      * @param hName 
  695.      *            集合名 
  696.      * @param key 
  697.      * @param val 
  698.      */  
  699.     public static <T> void hsetnx(String hName, String key, T t) {  
  700.         hsetnx(hName, key, JSON.toJSONString(t));  
  701.     }  
  702.   
  703. }  


2、重点来了,我们怎么叫我们的jar包加入自启动呢?首先加入autoconfig

  1. package com.ecej.nove.redis.core;  
  2.   
  3. import org.springframework.context.annotation.Configuration;  
  4. import org.springframework.context.annotation.Import;  
  5.   
  6. import com.ecej.nove.redis.config.RedisClusterConfig;  
  7. import com.ecej.nove.redis.config.RedisSentinelConfig;  
  8. import com.ecej.nove.redis.utils.JedisClusterUtils;  
  9.   
  10. @Configuration  
  11. @Import({ RedisClusterConfig.class, RedisSentinelConfig.class, JedisClusterUtils.class })  
  12. public class RedisAutoConfiguration {  
  13.   
  14. }  


在src\main\resources下面增加自启动扫描配置
META-INF/spring.factories

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.ecej.nove.redis.core.RedisAutoConfiguration



3、至此,配置就全部完成了,下面说下使用

说下redis使用,如果想在自己的项目中使用redis,如下先加入依赖

<dependency>

          <groupId>com.nove</groupId>
          <artifactId>xxx-redis</artifactId>
</dependency>

就可以了,然后我们只要配置我们的配置文件,不需要其他多余的工作
redis集群分为两种,sentinel 还有3.x的cluster,根据你自己的需要选择集群配置,配置文件都放在resources下面的
先说sentinel配置
用法:使用com.xxx.nove.redis.utils.JedisClusterUtils这个静态类
remote-redis.properties
这个大家可以直接下载用
xxx.redis.hostName=@xxx.redis.hostName@
xxx.redis.password=@xxx.redis.password@
xxx.redis.mastername=@xxx.redis.mastername@
以下配置可选择增加
xxx.redis.maxIdle=@xxx.redis.maxIdle@
xxx.redis.maxTotal=@xxx.redis.maxTotal@
xxx.redis.maxWaitMillis=@xxx.redis.maxWaitMillis@

这是properties的配置
下面说下POM里面profile的配置
<xxx.redis.hostName>10.32.32.58:26379,10.32.32.58:26380,10.32.32.58:26381</xxx.redis.hostName>
<xxx.redis.mastername>redismaster</xxx.redis.mastername>
<xxx.redis.password><![CDATA[4BZcIv&9]]></xxx.redis.password>
<xxx.redis.maxIdle>10</xxx.redis.maxIdle>
<xxx.redis.maxTotal>1000</xxx.redis.maxTotal>
<xxx.redis.maxWaitMillis>3000</xxx.redis.maxWaitMillis>

下面再说下3.x的配置
remote-redis.properties
xxx.redis.password=@xxx.redis.password@
xxx.redis.hostName=@xxx.redis.hostName@
以下配置可选择增加
xxx.redis.maxIdle=@xxx.redis.maxIdle@
xxx.redis.maxTotal=@xxx.redis.maxTotal@
xxx.redis.maxWaitMillis=@xxx.redis.maxWaitMillis@
xxx.redis.maxRedirects=@xxx.redis.maxRedirects@

下面贴出profile的配置
<xxx.redis.hostName>10.4.89.161:6379</xxx.redis.hostName>
<xxx.redis.maxRedirects>10</xxx.redis.maxRedirects>
<xxx.redis.password></xxx.redis.password>
<xxx.redis.maxIdle>10</xxx.redis.maxIdle>
<xxx.redis.maxTotal>1000</xxx.redis.maxTotal>
<xxx.redis.maxWaitMillis>3000</xxx.redis.maxWaitMillis>
两种配置都有了,那下面说下怎么选择用哪种集群模式
xxx.redis.cluster=true  使用3.x模式
xxx.redis.sentinel=true 使用sentinel模式
注意:这俩配置选一个,放在application.properties中,不要乱放。

OK,全部配置完成,可以开心的使用了

更多文章尽在本人公众号,计划每天推出一篇小结




本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
springboot之使用redistemplate优雅地操作redis
Java封装redis工具类
redis自学-redis工具类
Spring Cloud Redis 是如何实现点赞、取消点赞的?
使用Spring Data Redis操作Redis(一)
spring boot redis cache 缓存学习
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服