Spring Boot 实战 :集成 Redis

分手后的思念是犯贱 2022-02-04 06:45 309阅读 0赞

我们上篇文章写的是 Boot 的入门篇,集成了 MyBatis,所以这一章,就不在介绍 Boot 的详细使用了如果有不了解的朋友可以去看博主的上一篇文章:https://blog.csdn.net/qq_36537546/article/details/89842305

不说废话了,直接进入正题,首先介绍一下什么是 Redis ??

  1. redis 是一个开源的使用 ANSI [C语言][C]编写、支持网络、可基于内存亦可持久化的日志型、Key-Value [数据库][Link 1] Memcached 类似,它支持存储的 value 类型相对更多,包括 String(字符串)、List([链表][Link 2])、Set(集合)、Zset(Sorted set --有序集合) Hash(哈希类型),这些数据类型都支持 push/popadd/remove 及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的,在此基础上,redis 支持各种不同方式的排序。与 memcached 一样,为了保证效率,数据都是缓存在内存中,区别的是 redis 会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了 master-slave (主从)同步,redis 的出现,很大程度补偿了 memcached 这类 key/value 存储的不足,在部分场合可以对关系数据库起到很好的补充作用,它提供了 JavaC/C++,C\#PHPJavaScriptPerlObject-CPythonRubyErlang 等客户端,使用很方便,redis 支持主从同步,数据可以从主服务器向任意数量的从服务器上同步,从服务器可以是关联其他从服务器的主服务器。这使得 redis 可执行单层树复制,存盘可以有意无意的对数据进行写操作,由于完全实现了发布/订阅机制,使得从数据库在任何地方同步树时,可订阅一个频道并接收主服务器完整的消息发布记录,同步对读取操作的可扩展性和数据冗余很有帮助。

为什么要用 redis ??

  1. 在单机时代,存储只用一台机器装 mysql,如果每次存储成千上万条数据,这样很会导致 mysql 的性能很差,存储以及读取速度很慢,然后就演变成 缓存+mysql+垂直拆分 的方式,cache 作为中间缓存,将所有的数据先保存到缓存中,然后再存入mysql中,减小数据库压力,提高效率,但是当数据再次增加到又一个量级,上面的方式也不能满足需求,由于数据库的写入压力增加,缓存只能缓解数据库的读取压力,读写集中在一个数据库上让数据库不堪重负,大部分网站开始使用主从复制技术来达到读写分离,以提高读写性能和读库的可扩展性

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM2NTM3NTQ2_size_16_color_FFFFFF_t_70

为什么要选择 redis??

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM2NTM3NTQ2_size_16_color_FFFFFF_t_70 1

-————————————————————————— 关于 Redis 介绍到此结束 ———————————————————————————

首先配置 pom.xml 文件

  1. <dependency><!-- redis 依赖 -->
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>redis.clients</groupId>
  7. <artifactId>jedis</artifactId>
  8. <version>2.9.0</version>
  9. </dependency>

然后配置 application.properties

  1. ### Redis 缓存配置
  2. ### 默认 redis 数据库为 db 0
  3. spring.redis.database=0
  4. ### 服务器地址 127.0.0.1
  5. spring.redis.host=127.0.0.1
  6. ### 链接端口,默认6379
  7. spring.redis.port=6379
  8. ### redis 默认密码为空
  9. spring.redis.password=

依次配置 redis 的配置文件

redis.properties

  1. redis.hostName=127.0.0.1
  2. redis.port=6379
  3. redis.password=
  4. redis.timeout=10000
  5. redis.maxIdle=300
  6. redis.maxTotal=1000
  7. redis.maxWaitMillis=1000
  8. redis.minEvictableIdleTimeMillis=300000
  9. redis.numTestsPerEvictionRun=1024
  10. redis.timeBetweenEvictionRunsMillis=30000
  11. redis.testOnBorrow=true
  12. redis.testWhileIdle=true

JedisUtil

  1. package org.cs.redis.redis;
  2. import com.alibaba.druid.util.StringUtils;
  3. import org.apache.log4j.Logger;
  4. import redis.clients.jedis.Jedis;
  5. import redis.clients.jedis.JedisPool;
  6. import redis.clients.jedis.JedisPoolConfig;
  7. import java.util.concurrent.locks.ReentrantLock;
  8. /**
  9. * @title: JedisUtil
  10. * @auther: linluochen
  11. * @date: 2019/5/7 9:39
  12. */
  13. public class JedisUtil {
  14. protected static ReentrantLock lockPool = new ReentrantLock();
  15. protected static ReentrantLock lockJedis = new ReentrantLock();
  16. protected static Logger logger = Logger.getLogger(JedisUtil.class);
  17. //Redis服务器IP
  18. private static String ADDR_ARRAY = "127.0.0.1";
  19. //Redis的端口号
  20. private static int PORT = 6379;
  21. //访问密码
  22. private static String AUTH = "";
  23. //可用连接实例的最大数目,默认值为8;
  24. //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
  25. private static int MAX_ACTIVE = 300;
  26. //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
  27. private static int MAX_IDLE = 8;
  28. //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
  29. private static int MAX_WAIT = 3000;
  30. //超时时间
  31. private static int TIMEOUT = 10000;
  32. //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
  33. private static boolean TEST_ON_BORROW = true;
  34. private static boolean TEST_WhileIdle = true;
  35. private static JedisPool jedisPool = null;
  36. /**
  37. * redis过期时间,以秒为单位
  38. */
  39. public final static int EXRP_HOUR = 60 * 60; //一小时
  40. public final static int EXRP_DAY = 60 * 60 * 24; //一天
  41. public final static int EXRP_MONTH = 60 * 60 * 24 * 30; //一个月
  42. /**
  43. * 初始化Redis连接池
  44. */
  45. private static void initialPool() {
  46. try {
  47. JedisPoolConfig config = new JedisPoolConfig();
  48. config.setMaxTotal(MAX_ACTIVE);
  49. config.setMaxIdle(MAX_IDLE);
  50. config.setMaxWaitMillis(MAX_WAIT);
  51. config.setTestOnBorrow(TEST_ON_BORROW);
  52. config.setTestWhileIdle(TEST_WhileIdle);
  53. jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[0], PORT, TIMEOUT, AUTH,0);
  54. } catch (Exception e) {
  55. logger.error("First create JedisPool error : " + e);
  56. try {
  57. //如果第一个IP异常,则访问第二个IP
  58. JedisPoolConfig config = new JedisPoolConfig();
  59. config.setMaxTotal(MAX_ACTIVE);
  60. config.setMaxIdle(MAX_IDLE);
  61. config.setMaxWaitMillis(MAX_WAIT);
  62. config.setTestOnBorrow(TEST_ON_BORROW);
  63. config.setTestWhileIdle(TEST_WhileIdle);
  64. jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[1], PORT, TIMEOUT, AUTH,0);
  65. } catch (Exception e2) {
  66. logger.error("Second create JedisPool error : " + e2);
  67. }
  68. }
  69. }
  70. /**
  71. * 在多线程环境同步初始化
  72. */
  73. private static void poolInit() {
  74. lockPool.lock();
  75. try {
  76. if (jedisPool == null) {
  77. initialPool();
  78. }
  79. } catch (Exception e) {
  80. e.printStackTrace();
  81. } finally {
  82. lockPool.unlock();
  83. }
  84. }
  85. public static Jedis getJedis() {
  86. lockJedis.lock();
  87. if (jedisPool == null) {
  88. poolInit();
  89. }
  90. Jedis jedis = null;
  91. try {
  92. if (jedisPool != null) {
  93. jedis = jedisPool.getResource();
  94. }
  95. } catch (Exception e) {
  96. logger.error("Get jedis error : " + e);
  97. } finally {
  98. returnResource(jedis);
  99. lockJedis.unlock();
  100. }
  101. return jedis;
  102. }
  103. /**
  104. * 释放jedis资源
  105. *
  106. * @param jedis
  107. */
  108. public static void returnResource(final Jedis jedis) {
  109. if (jedis != null && jedisPool != null) {
  110. jedisPool.returnResource(jedis);
  111. }
  112. }
  113. /**
  114. * 设置 String
  115. *
  116. * @param key
  117. * @param value
  118. */
  119. public synchronized static void setString(String key, String value) {
  120. try {
  121. value = StringUtils.isEmpty(value) ? "" : value;
  122. getJedis().set(key, value);
  123. } catch (Exception e) {
  124. logger.error("Set key error : " + e);
  125. }
  126. }
  127. /**
  128. * 设置 过期时间
  129. *
  130. * @param key
  131. * @param seconds 以秒为单位
  132. * @param value
  133. */
  134. public synchronized static void setString(String key, int seconds, String value) {
  135. try {
  136. value = StringUtils.isEmpty(value) ? "" : value;
  137. getJedis().setex(key, seconds, value);
  138. } catch (Exception e) {
  139. logger.error("Set keyex error : " + e);
  140. }
  141. }
  142. /**
  143. * 删除
  144. *
  145. * @param key
  146. */
  147. public synchronized static void delString(String key) {
  148. try {
  149. if(!StringUtils.isEmpty(key)) {
  150. getJedis().del(key);
  151. }
  152. } catch (Exception e) {
  153. logger.error("Set key error : " + e);
  154. }
  155. }
  156. /**
  157. * 获取String值
  158. *
  159. * @param key
  160. * @return value
  161. */
  162. public synchronized static String getString(String key) {
  163. if (getJedis() == null || !getJedis().exists(key)) {
  164. return null;
  165. }
  166. return getJedis().get(key);
  167. }
  168. }

RedisConfig

  1. package org.cs.redis.redis;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.context.annotation.PropertySource;
  6. import org.springframework.data.redis.connection.RedisConnectionFactory;
  7. import org.springframework.data.redis.connection.RedisPassword;
  8. import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
  9. import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
  10. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
  11. import org.springframework.data.redis.core.RedisTemplate;
  12. import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
  13. import org.springframework.data.redis.serializer.StringRedisSerializer;
  14. import redis.clients.jedis.JedisPoolConfig;
  15. @Configuration
  16. @PropertySource("classpath:config/redis.properties")
  17. public class RedisConfig {
  18. @Value("${redis.hostName}")
  19. private String hostName;
  20. @Value("${redis.port}")
  21. private Integer port;
  22. @Value("${redis.password}")
  23. private String password;
  24. @Value("${redis.timeout}")
  25. private Integer timeout;
  26. @Value("${redis.maxIdle}")
  27. private Integer maxIdle;
  28. @Value("${redis.maxTotal}")
  29. private Integer maxTotal;
  30. @Value("${redis.maxWaitMillis}")
  31. private Integer maxWaitMillis;
  32. @Value("${redis.minEvictableIdleTimeMillis}")
  33. private Integer minEvictableIdleTimeMillis;
  34. @Value("${redis.numTestsPerEvictionRun}")
  35. private Integer numTestsPerEvictionRun;
  36. @Value("${redis.timeBetweenEvictionRunsMillis}")
  37. private long timeBetweenEvictionRunsMillis;
  38. @Value("${redis.testOnBorrow}")
  39. private boolean testOnBorrow;
  40. @Value("${redis.testWhileIdle}")
  41. private boolean testWhileIdle;
  42. /*@Value("${spring.redis.cluster.nodes}")
  43. private String clusterNodes; */
  44. /*@Value("${spring.redis.cluster.max-redirects}")
  45. private Integer mmaxRedirectsac;*/
  46. /**
  47. * JedisPoolConfig 连接池
  48. * @return
  49. */
  50. @Bean
  51. public JedisPoolConfig jedisPoolConfig() {
  52. JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
  53. // 最大空闲数
  54. jedisPoolConfig.setMaxIdle(maxIdle);
  55. // 连接池的最大数据库连接数
  56. jedisPoolConfig.setMaxTotal(maxTotal);
  57. // 最大建立连接等待时间
  58. jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
  59. // 逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
  60. jedisPoolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  61. // 每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
  62. jedisPoolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
  63. // 逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
  64. jedisPoolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  65. // 是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
  66. jedisPoolConfig.setTestOnBorrow(testOnBorrow);
  67. // 在空闲时检查有效性, 默认false
  68. jedisPoolConfig.setTestWhileIdle(testWhileIdle);
  69. return jedisPoolConfig;
  70. }
  71. /**
  72. * 单机版配置
  73. * @Title: JedisConnectionFactory
  74. * @param @param jedisPoolConfig
  75. * @param @return
  76. * @return JedisConnectionFactory
  77. * @autor Alex
  78. * @date 2019年3月18日
  79. * @throws
  80. */
  81. @Bean
  82. public JedisConnectionFactory JedisConnectionFactory(JedisPoolConfig jedisPoolConfig){
  83. //单机版jedis
  84. RedisStandaloneConfiguration redisStandaloneConfiguration =
  85. new RedisStandaloneConfiguration();
  86. //设置redis服务器的host或者ip地址
  87. redisStandaloneConfiguration.setHostName(hostName);
  88. //设置默认使用的数据库
  89. redisStandaloneConfiguration.setDatabase(0);
  90. //设置密码
  91. redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
  92. //设置redis的服务的端口号
  93. redisStandaloneConfiguration.setPort(port);
  94. //获得默认的连接池构造器(怎么设计的,为什么不抽象出单独类,供用户使用呢)
  95. JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb =
  96. (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder)JedisClientConfiguration.builder();
  97. //指定jedisPoolConifig来修改默认的连接池构造器(真麻烦,滥用设计模式!)
  98. jpcb.poolConfig(jedisPoolConfig);
  99. //通过构造器来构造jedis客户端配置
  100. JedisClientConfiguration jedisClientConfiguration = jpcb.build();
  101. //单机配置 + 客户端配置 = jedis连接工厂
  102. return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
  103. /*RedisStandaloneConfiguration redisStandaloneConfiguration=new RedisStandaloneConfiguration();
  104. redisStandaloneConfiguration.setHostName(hostName);
  105. redisStandaloneConfiguration.setPort(port);
  106. redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
  107. redisStandaloneConfiguration.setDatabase(0);
  108. return new JedisConnectionFactory(redisStandaloneConfiguration);*/
  109. //return JedisConnectionFactory;
  110. }
  111. /**
  112. * 实例化 RedisTemplate 对象
  113. *
  114. * @return
  115. */
  116. @Bean
  117. public RedisTemplate<String, Object> functionDomainRedisTemplate() {
  118. RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
  119. initDomainRedisTemplate(redisTemplate, JedisConnectionFactory(jedisPoolConfig()));
  120. return redisTemplate;
  121. }
  122. /**
  123. * 设置数据存入 redis 的序列化方式,并开启事务
  124. * @autor Alex
  125. * @param redisTemplate
  126. * @param factory
  127. */
  128. private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
  129. //如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!
  130. redisTemplate.setKeySerializer(new StringRedisSerializer());
  131. redisTemplate.setHashKeySerializer(new StringRedisSerializer());
  132. redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
  133. redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
  134. // 开启事务
  135. redisTemplate.setEnableTransactionSupport(true);
  136. redisTemplate.setConnectionFactory(factory);
  137. redisTemplate.afterPropertiesSet();
  138. }
  139. /**
  140. * 注入redisUtil
  141. * @Title: redisUtil
  142. * @param @param redisTemplate
  143. * @param @return
  144. * @return RedisUtil
  145. * @autor Alex
  146. * @date 2018年8月17日
  147. * @throws
  148. */
  149. @Bean(name = "redisUtil")
  150. public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate) {
  151. RedisUtil redisUtil = new RedisUtil();
  152. redisUtil.setRedisTemplate(redisTemplate);
  153. return redisUtil;
  154. }
  155. }

RedisUtil

  1. package org.cs.redis.redis;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.data.redis.core.RedisTemplate;
  4. import org.springframework.util.CollectionUtils;
  5. import java.util.List;
  6. import java.util.Map;
  7. import java.util.Set;
  8. import java.util.concurrent.TimeUnit;
  9. /**
  10. * @title: redis 工具类
  11. * @auther: linluochen
  12. * @date: 2019/5/7 9:41
  13. */
  14. public class RedisUtil {
  15. @Autowired
  16. private RedisTemplate<String, Object> redisTemplate;
  17. public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
  18. this.redisTemplate = redisTemplate;
  19. }
  20. //=============================common============================
  21. /**
  22. * 指定缓存失效时间
  23. * @param key 键
  24. * @param time 时间(秒)
  25. * @return
  26. */
  27. public boolean expire(String key,long time){
  28. try {
  29. if(time>0){
  30. redisTemplate.expire(key, time, TimeUnit.SECONDS);
  31. }
  32. return true;
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. return false;
  36. }
  37. }
  38. /**
  39. * 根据key 获取过期时间
  40. * @param key 键 不能为null
  41. * @return 时间(秒) 返回0代表为永久有效
  42. */
  43. public long getExpire(String key){
  44. return redisTemplate.getExpire(key,TimeUnit.SECONDS);
  45. }
  46. /**
  47. * 判断key是否存在
  48. * @param key 键
  49. * @return true 存在 false不存在
  50. */
  51. public boolean hasKey(String key){
  52. try {
  53. return redisTemplate.hasKey(key);
  54. } catch (Exception e) {
  55. e.printStackTrace();
  56. return false;
  57. }
  58. }
  59. /**
  60. * 删除缓存
  61. * @param key 可以传一个值 或多个
  62. */
  63. public void del(String ... key){
  64. if(key!=null&&key.length>0){
  65. if(key.length==1){
  66. redisTemplate.delete(key[0]);
  67. }else{
  68. redisTemplate.delete(CollectionUtils.arrayToList(key));
  69. }
  70. }
  71. }
  72. //============================String=============================
  73. /**
  74. * 普通缓存获取
  75. * @param key 键
  76. * @return 值
  77. */
  78. public Object get(String key){
  79. return key==null?null:redisTemplate.opsForValue().get(key);
  80. }
  81. /**
  82. * 普通缓存放入
  83. * @param key 键
  84. * @param value 值
  85. * @return true成功 false失败
  86. */
  87. public boolean set(String key,Object value) {
  88. try {
  89. redisTemplate.opsForValue().set(key, value);
  90. return true;
  91. } catch (Exception e) {
  92. e.printStackTrace();
  93. return false;
  94. }
  95. }
  96. /**
  97. * 普通缓存放入并设置时间
  98. * @param key 键
  99. * @param value 值
  100. * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
  101. * @return true成功 false 失败
  102. */
  103. public boolean set(String key,Object value,long time){
  104. try {
  105. if(time>0){
  106. redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
  107. }else{
  108. set(key, value);
  109. }
  110. return true;
  111. } catch (Exception e) {
  112. e.printStackTrace();
  113. return false;
  114. }
  115. }
  116. /**
  117. * 递增
  118. * @param key 键
  119. * @return
  120. */
  121. public long incr(String key, long delta){
  122. if(delta<0){
  123. throw new RuntimeException("递增因子必须大于0");
  124. }
  125. return redisTemplate.opsForValue().increment(key, delta);
  126. }
  127. /**
  128. * 递减
  129. * @param key 键
  130. * @return
  131. */
  132. public long decr(String key, long delta){
  133. if(delta<0){
  134. throw new RuntimeException("递减因子必须大于0");
  135. }
  136. return redisTemplate.opsForValue().increment(key, -delta);
  137. }
  138. //================================Map=================================
  139. /**
  140. * HashGet
  141. * @param key 键 不能为null
  142. * @param item 项 不能为null
  143. * @return 值
  144. */
  145. public Object hget(String key,String item){
  146. return redisTemplate.opsForHash().get(key, item);
  147. }
  148. /**
  149. * 获取hashKey对应的所有键值
  150. * @param key 键
  151. * @return 对应的多个键值
  152. */
  153. public Map<Object,Object> hmget(String key){
  154. return redisTemplate.opsForHash().entries(key);
  155. }
  156. /**
  157. * HashSet
  158. * @param key 键
  159. * @param map 对应多个键值
  160. * @return true 成功 false 失败
  161. */
  162. public boolean hmset(String key, Map<String,Object> map){
  163. try {
  164. redisTemplate.opsForHash().putAll(key, map);
  165. return true;
  166. } catch (Exception e) {
  167. e.printStackTrace();
  168. return false;
  169. }
  170. }
  171. /**
  172. * HashSet 并设置时间
  173. * @param key 键
  174. * @param map 对应多个键值
  175. * @param time 时间(秒)
  176. * @return true成功 false失败
  177. */
  178. public boolean hmset(String key, Map<String,Object> map, long time){
  179. try {
  180. redisTemplate.opsForHash().putAll(key, map);
  181. if(time>0){
  182. expire(key, time);
  183. }
  184. return true;
  185. } catch (Exception e) {
  186. e.printStackTrace();
  187. return false;
  188. }
  189. }
  190. /**
  191. * 向一张hash表中放入数据,如果不存在将创建
  192. * @param key 键
  193. * @param item 项
  194. * @param value 值
  195. * @return true 成功 false失败
  196. */
  197. public boolean hset(String key,String item,Object value) {
  198. try {
  199. redisTemplate.opsForHash().put(key, item, value);
  200. return true;
  201. } catch (Exception e) {
  202. e.printStackTrace();
  203. return false;
  204. }
  205. }
  206. /**
  207. * 向一张hash表中放入数据,如果不存在将创建
  208. * @param key 键
  209. * @param item 项
  210. * @param value 值
  211. * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
  212. * @return true 成功 false失败
  213. */
  214. public boolean hset(String key,String item,Object value,long time) {
  215. try {
  216. redisTemplate.opsForHash().put(key, item, value);
  217. if(time>0){
  218. expire(key, time);
  219. }
  220. return true;
  221. } catch (Exception e) {
  222. e.printStackTrace();
  223. return false;
  224. }
  225. }
  226. /**
  227. * 删除hash表中的值
  228. * @param key 键 不能为null
  229. * @param item 项 可以使多个 不能为null
  230. */
  231. public void hdel(String key, Object... item){
  232. redisTemplate.opsForHash().delete(key,item);
  233. }
  234. /**
  235. * 判断hash表中是否有该项的值
  236. * @param key 键 不能为null
  237. * @param item 项 不能为null
  238. * @return true 存在 false不存在
  239. */
  240. public boolean hHasKey(String key, String item){
  241. return redisTemplate.opsForHash().hasKey(key, item);
  242. }
  243. /**
  244. * hash递增 如果不存在,就会创建一个 并把新增后的值返回
  245. * @param key 键
  246. * @param item 项
  247. * @param by 要增加几(大于0)
  248. * @return
  249. */
  250. public double hincr(String key, String item,double by){
  251. return redisTemplate.opsForHash().increment(key, item, by);
  252. }
  253. /**
  254. * hash递减
  255. * @param key 键
  256. * @param item 项
  257. * @param by 要减少记(小于0)
  258. * @return
  259. */
  260. public double hdecr(String key, String item,double by){
  261. return redisTemplate.opsForHash().increment(key, item,-by);
  262. }
  263. //============================set=============================
  264. /**
  265. * 根据key获取Set中的所有值
  266. * @param key 键
  267. * @return
  268. */
  269. public Set<Object> sGet(String key){
  270. try {
  271. return redisTemplate.opsForSet().members(key);
  272. } catch (Exception e) {
  273. e.printStackTrace();
  274. return null;
  275. }
  276. }
  277. /**
  278. * 根据value从一个set中查询,是否存在
  279. * @param key 键
  280. * @param value 值
  281. * @return true 存在 false不存在
  282. */
  283. public boolean sHasKey(String key,Object value){
  284. try {
  285. return redisTemplate.opsForSet().isMember(key, value);
  286. } catch (Exception e) {
  287. e.printStackTrace();
  288. return false;
  289. }
  290. }
  291. /**
  292. * 将数据放入set缓存
  293. * @param key 键
  294. * @param values 值 可以是多个
  295. * @return 成功个数
  296. */
  297. public long sSet(String key, Object...values) {
  298. try {
  299. return redisTemplate.opsForSet().add(key, values);
  300. } catch (Exception e) {
  301. e.printStackTrace();
  302. return 0;
  303. }
  304. }
  305. /**
  306. * 将set数据放入缓存
  307. * @param key 键
  308. * @param time 时间(秒)
  309. * @param values 值 可以是多个
  310. * @return 成功个数
  311. */
  312. public long sSetAndTime(String key,long time,Object...values) {
  313. try {
  314. Long count = redisTemplate.opsForSet().add(key, values);
  315. if(time>0) expire(key, time);
  316. return count;
  317. } catch (Exception e) {
  318. e.printStackTrace();
  319. return 0;
  320. }
  321. }
  322. /**
  323. * 获取set缓存的长度
  324. * @param key 键
  325. * @return
  326. */
  327. public long sGetSetSize(String key){
  328. try {
  329. return redisTemplate.opsForSet().size(key);
  330. } catch (Exception e) {
  331. e.printStackTrace();
  332. return 0;
  333. }
  334. }
  335. /**
  336. * 移除值为value的
  337. * @param key 键
  338. * @param values 值 可以是多个
  339. * @return 移除的个数
  340. */
  341. public long setRemove(String key, Object ...values) {
  342. try {
  343. Long count = redisTemplate.opsForSet().remove(key, values);
  344. return count;
  345. } catch (Exception e) {
  346. e.printStackTrace();
  347. return 0;
  348. }
  349. }
  350. //===============================list=================================
  351. /**
  352. * 获取list缓存的内容
  353. * @param key 键
  354. * @param start 开始
  355. * @param end 结束 0 到 -1代表所有值
  356. * @return
  357. */
  358. public List<Object> lGet(String key,long start, long end){
  359. try {
  360. return redisTemplate.opsForList().range(key, start, end);
  361. } catch (Exception e) {
  362. e.printStackTrace();
  363. return null;
  364. }
  365. }
  366. /**
  367. * 获取list缓存的长度
  368. * @param key 键
  369. * @return
  370. */
  371. public long lGetListSize(String key){
  372. try {
  373. return redisTemplate.opsForList().size(key);
  374. } catch (Exception e) {
  375. e.printStackTrace();
  376. return 0;
  377. }
  378. }
  379. /**
  380. * 通过索引 获取list中的值
  381. * @param key 键
  382. * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
  383. * @return
  384. */
  385. public Object lGetIndex(String key,long index){
  386. try {
  387. return redisTemplate.opsForList().index(key, index);
  388. } catch (Exception e) {
  389. e.printStackTrace();
  390. return null;
  391. }
  392. }
  393. /**
  394. * 将list放入缓存
  395. * @param key 键
  396. * @param value 值
  397. * @return
  398. */
  399. public boolean lSet(String key, Object value) {
  400. try {
  401. redisTemplate.opsForList().rightPush(key, value);
  402. return true;
  403. } catch (Exception e) {
  404. e.printStackTrace();
  405. return false;
  406. }
  407. }
  408. /**
  409. * 将list放入缓存
  410. * @param key 键
  411. * @param value 值
  412. * @param time 时间(秒)
  413. * @return
  414. */
  415. public boolean lSet(String key, Object value, long time) {
  416. try {
  417. redisTemplate.opsForList().rightPush(key, value);
  418. if (time > 0) expire(key, time);
  419. return true;
  420. } catch (Exception e) {
  421. e.printStackTrace();
  422. return false;
  423. }
  424. }
  425. /**
  426. * 将list放入缓存
  427. * @param key 键
  428. * @param value 值
  429. * @return
  430. */
  431. public boolean lSet(String key, List<Object> value) {
  432. try {
  433. redisTemplate.opsForList().rightPushAll(key, value);
  434. return true;
  435. } catch (Exception e) {
  436. e.printStackTrace();
  437. return false;
  438. }
  439. }
  440. /**
  441. * 将list放入缓存
  442. * @param key 键
  443. * @param value 值
  444. * @param time 时间(秒)
  445. * @return
  446. */
  447. public boolean lSet(String key, List<Object> value, long time) {
  448. try {
  449. redisTemplate.opsForList().rightPushAll(key, value);
  450. if (time > 0) expire(key, time);
  451. return true;
  452. } catch (Exception e) {
  453. e.printStackTrace();
  454. return false;
  455. }
  456. }
  457. /**
  458. * 根据索引修改list中的某条数据
  459. * @param key 键
  460. * @param index 索引
  461. * @param value 值
  462. * @return
  463. */
  464. public boolean lUpdateIndex(String key, long index,Object value) {
  465. try {
  466. redisTemplate.opsForList().set(key, index, value);
  467. return true;
  468. } catch (Exception e) {
  469. e.printStackTrace();
  470. return false;
  471. }
  472. }
  473. /**
  474. * 移除N个值为value
  475. * @param key 键
  476. * @param count 移除多少个
  477. * @param value 值
  478. * @return 移除的个数
  479. */
  480. public long lRemove(String key,long count,Object value) {
  481. try {
  482. Long remove = redisTemplate.opsForList().remove(key, count, value);
  483. return remove;
  484. } catch (Exception e) {
  485. e.printStackTrace();
  486. return 0;
  487. }
  488. }
  489. }

配置完成后测试调用:

  1. package com.cs.redis;
  2. import com.cs.redis.config.RedisUtil;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import org.springframework.test.context.junit4.SpringRunner;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. @RunWith(SpringRunner.class)
  11. @SpringBootTest
  12. public class RedisApplicationTests {
  13. @Autowired
  14. RedisUtil redisUtil;
  15. @Test
  16. public void contextLoads() {
  17. }
  18. @Test
  19. public void RedisTest(){
  20. Map<String,Object> map = new HashMap<String, Object>();
  21. String luochen = "linluochen"; // 定义它 Key 的名称
  22. String search = "小洛儿"; // 定义它的 Value
  23. redisUtil.set(luochen,search); // 放进 redis 里
  24. String redis = (String) redisUtil.get(luochen); //取出值的时候直接去 Key 的名字就可以了,因为取出的值是object类型的所以需要给他强制转换一下
  25. System.out.println("结果为:"+redis); //输出结果
  26. /*List<String> list = (List<String>) redisUtil.get(luochen);
  27. if(StringUtils.isNotBlank(search)) {
  28. if(list != null) {
  29. list.add(0,search);
  30. redisUtil.set(luochen, list,60L*60*24*30);
  31. map.put("historical",list.size()<=6?list:list.subList(0, 6));
  32. }else {
  33. List<String> searchList = new ArrayList<String>();
  34. searchList.add(search);
  35. redisUtil.set(luochen, searchList,60L*60*24*30);
  36. map.put("historical",searchList);
  37. }
  38. System.out.println("执行成功 !!!!"+map); // 打印值
  39. }else {
  40. map.put("historical",list.size()<=6?list:list.subList(0, 6));
  41. }*/
  42. }
  43. }

调用结果为:

20190507104508272.png

示例地址:https://download.csdn.net/download/qq_36537546/11163687

发表评论

表情:
评论列表 (有 0 条评论,309人围观)

还没有评论,来说两句吧...

相关阅读