IT评测·应用市场-qidao123.com

标题: Spring Boot 中使用 Redis [打印本页]

作者: 张国伟    时间: 2023-4-14 17:03
标题: Spring Boot 中使用 Redis
Redis 环境

redis 安装、配置,启动:(此处以云服务器上进行说明)
  1. 下载地址:https://redis.io/download/
  2. 下载后上传到云服务器上,如 /usr/local 中
  3. gcc 环境安装:yum install -y gcc-c++
  4. 解压:tar -zxvf xxx
  5. 进入解压后的 redis 目录下执行
  6. 编译:make
  7. 安装:make install
  8. 下载 redis/bin/redis.conf 进行下列配置后上传覆盖原文件:
  9. 1. 注释掉 bind 127.0.0.1
  10. 2. 设置 protected-mode 为 no
  11. 3. 建议设置密码 requirepass xxx
  12. 在 redis/bin 下执行命令使用配置文件方式后台启动 redis:
  13. ./redis-server redis.conf &
  14. 查看 redis 启动状态:
  15. ps -ef|grep redis
  16. 其他:
  17. 关闭 redis:redis-cli shutdown
  18. 连接问题参考:
  19. 1. 终端执行,防火墙放行:firewall-cmd --zone=public --add-port=6379/tcp --permanent
  20. 2. 终端执行,防火墙重启:firewall-cmd --reload
  21. 3. 云服务器端口开放问题:在实例-》安全组管理中开放 6379 端口
复制代码
Spring Boot 中使用 Redis

1. 添加 pom
  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
复制代码
2. 添加配置
  1. spring:
  2.   redis:
  3.     database: 0
  4.     host: xxxxx      # Redis服务器地址,修改为你的地址
  5.     port: 6379              # Redis服务器连接端口
  6.     password: xxxxx          # Redis服务器连接密码(默认为空)
  7.     timeout: 3000           # Redis服务器链接超时配置
复制代码
3. 导入 redis 工具类

PS:redis 工具类对常用操作进行了封装,可自行研究食用。
  1. /**
  2. * Redis 工具类
  3. */
  4. @Component
  5. public class RedisUtil {
  6.     @Resource
  7.     private RedisTemplate<String, Object> redisTemplate;
  8.     // public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
  9.     //     this.redisTemplate = redisTemplate;
  10.     // }
  11.     /**
  12.      * 指定缓存失效时间
  13.      *
  14.      * @param key  键
  15.      * @param time 时间(秒)
  16.      * @return
  17.      */
  18.     public boolean expire(String key, long time) {
  19.         try {
  20.             if (time > 0) {
  21.                 redisTemplate.expire(key, time, TimeUnit.SECONDS);
  22.             }
  23.             return true;
  24.         } catch (Exception e) {
  25.             e.printStackTrace();
  26.             return false;
  27.         }
  28.     }
  29.     /**
  30.      * 根据key 获取过期时间
  31.      *
  32.      * @param key 键 不能为null
  33.      * @return 时间(秒) 返回0代表为永久有效
  34.      */
  35.     public long getExpire(String key) {
  36.         return redisTemplate.getExpire(key, TimeUnit.SECONDS);
  37.     }
  38.     /**
  39.      * 判断key是否存在
  40.      *
  41.      * @param key 键
  42.      * @return true 存在 false不存在
  43.      */
  44.     public boolean hasKey(String key) {
  45.         try {
  46.             return redisTemplate.hasKey(key);
  47.         } catch (Exception e) {
  48.             e.printStackTrace();
  49.             return false;
  50.         }
  51.     }
  52.     /**
  53.      * 删除缓存
  54.      *
  55.      * @param key 可以传一个值 或多个
  56.      */
  57.     @SuppressWarnings("unchecked")
  58.     public void del(String... key) {
  59.         if (key != null && key.length > 0) {
  60.             if (key.length == 1) {
  61.                 redisTemplate.delete(key[0]);
  62.             } else {
  63.                 redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
  64.             }
  65.         }
  66.     }
  67.     //============================String=============================
  68.     /**
  69.      * 普通缓存获取
  70.      *
  71.      * @param key 键
  72.      * @return 值
  73.      */
  74.     public Object get(String key) {
  75.         return key == null ? null : redisTemplate.opsForValue().get(key);
  76.     }
  77.     /**
  78.      * 普通缓存放入
  79.      *
  80.      * @param key   键
  81.      * @param value 值
  82.      * @return true成功 false失败
  83.      */
  84.     public boolean set(String key, Object value) {
  85.         try {
  86.             redisTemplate.opsForValue().set(key, value);
  87.             return true;
  88.         } catch (Exception e) {
  89.             e.printStackTrace();
  90.             return false;
  91.         }
  92.     }
  93.     /**
  94.      * 普通缓存放入并设置时间
  95.      *
  96.      * @param key   键
  97.      * @param value 值
  98.      * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
  99.      * @return true成功 false 失败
  100.      */
  101.     public boolean set(String key, Object value, long time) {
  102.         try {
  103.             if (time > 0) {
  104.                 redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
  105.             } else {
  106.                 set(key, value);
  107.             }
  108.             return true;
  109.         } catch (Exception e) {
  110.             e.printStackTrace();
  111.             return false;
  112.         }
  113.     }
  114.     /**
  115.      * 分布式锁
  116.      * @param key               锁住的key
  117.      * @param lockExpireMils    锁住的时长。如果超时未解锁,视为加锁线程死亡,其他线程可夺取锁
  118.      * @return
  119.      */
  120.     public boolean setNx(String key, Long lockExpireMils) {
  121.         // new RedisCallback<>() {
  122.         //     @Override
  123.         //     public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
  124.         //         return null;
  125.         //     }
  126.         // };
  127.         return (boolean) redisTemplate.execute((RedisCallback) connection -> {
  128.             //获取锁
  129.             /*
  130.               setNX(k,v):如果该键不存在,则设置该键的值为指定的字符串;否则不做任何事情;
  131.               使用 setNX() 命令可以实现分布式锁等功能,因为该命令在设置键值对时是具有原子性的。
  132.               在多线程或多进程环境中,如果多个线程或进程同时尝试使用 setNX() 命令来设置同一个键,
  133.               只有一个线程或进程能够成功地设置,其他线程或进程会失败,从而实现了互斥操作。
  134.              */
  135.             return connection.setNX(key.getBytes(), String.valueOf(System.currentTimeMillis() + lockExpireMils + 1).getBytes());
  136.         });
  137.     }
  138.     /**
  139.      * 递增
  140.      *
  141.      * @param key   键
  142.      * @param delta 要增加几(大于0)
  143.      * @return
  144.      */
  145.     public long incr(String key, long delta) {
  146.         if (delta < 0) {
  147.             throw new RuntimeException("递增因子必须大于0");
  148.         }
  149.         // 将指定 key 的值增加 delta。如果 key 不存在,则会先创建一个初始值为 0 的 key,然后再执行增加操作。
  150.         return redisTemplate.opsForValue().increment(key, delta);
  151.     }
  152.     /**
  153.      * 递减
  154.      *
  155.      * @param key   键
  156.      * @param delta 要减少几(小于0)
  157.      * @return
  158.      */
  159.     public long decr(String key, long delta) {
  160.         if (delta < 0) {
  161.             throw new RuntimeException("递减因子必须大于0");
  162.         }
  163.         return redisTemplate.opsForValue().increment(key, -delta);
  164.     }
  165.     //================================Map=================================
  166.     /**
  167.      * HashGet
  168.      *
  169.      * @param key  键 不能为null
  170.      * @param item 项 不能为null
  171.      * @return 值
  172.      */
  173.     public Object hget(String key, String item) {
  174.         return redisTemplate.opsForHash().get(key, item);
  175.     }
  176.     /**
  177.      * 获取hashKey对应的所有键值
  178.      *
  179.      * @param key 键
  180.      * @return 对应的多个键值
  181.      */
  182.     public Map<Object, Object> hmget(String key) {
  183.         return redisTemplate.opsForHash().entries(key);
  184.     }
  185.     /**
  186.      * HashSet
  187.      *
  188.      * @param key 键
  189.      * @param map 对应多个键值
  190.      * @return true 成功 false 失败
  191.      */
  192.     public boolean hmset(String key, Map<String, Object> map) {
  193.         try {
  194.             redisTemplate.opsForHash().putAll(key, map);
  195.             return true;
  196.         } catch (Exception e) {
  197.             e.printStackTrace();
  198.             return false;
  199.         }
  200.     }
  201.     /**
  202.      * HashSet 并设置时间
  203.      *
  204.      * @param key  键
  205.      * @param map  对应多个键值
  206.      * @param time 时间(秒)
  207.      * @return true成功 false失败
  208.      */
  209.     public boolean hmset(String key, Map<String, Object> map, long time) {
  210.         try {
  211.             redisTemplate.opsForHash().putAll(key, map);
  212.             if (time > 0) {
  213.                 expire(key, time);
  214.             }
  215.             return true;
  216.         } catch (Exception e) {
  217.             e.printStackTrace();
  218.             return false;
  219.         }
  220.     }
  221.     /**
  222.      * 向一张hash表中放入数据,如果不存在将创建
  223.      *
  224.      * @param key   键
  225.      * @param item  项
  226.      * @param value 值
  227.      * @return true 成功 false失败
  228.      */
  229.     public boolean hset(String key, String item, Object value) {
  230.         try {
  231.             redisTemplate.opsForHash().put(key, item, value);
  232.             return true;
  233.         } catch (Exception e) {
  234.             e.printStackTrace();
  235.             return false;
  236.         }
  237.     }
  238.     /**
  239.      * 向一张hash表中放入数据,如果不存在将创建
  240.      *
  241.      * @param key   键
  242.      * @param item  项
  243.      * @param value 值
  244.      * @param time  时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间
  245.      * @return true 成功 false失败
  246.      */
  247.     public boolean hset(String key, String item, Object value, long time) {
  248.         try {
  249.             redisTemplate.opsForHash().put(key, item, value);
  250.             if (time > 0) {
  251.                 expire(key, time);
  252.             }
  253.             return true;
  254.         } catch (Exception e) {
  255.             e.printStackTrace();
  256.             return false;
  257.         }
  258.     }
  259.     /**
  260.      * 删除hash表中的值
  261.      *
  262.      * @param key  键 不能为null
  263.      * @param item 项 可以使多个 不能为null
  264.      */
  265.     public void hdel(String key, Object... item) {
  266.         redisTemplate.opsForHash().delete(key, item);
  267.     }
  268.     /**
  269.      * 判断hash表中是否有该项的值
  270.      *
  271.      * @param key  键 不能为null
  272.      * @param item 项 不能为null
  273.      * @return true 存在 false不存在
  274.      */
  275.     public boolean hHasKey(String key, String item) {
  276.         return redisTemplate.opsForHash().hasKey(key, item);
  277.     }
  278.     /**
  279.      * hash递增 如果不存在,就会创建一个 并把新增后的值返回
  280.      *
  281.      * @param key  键
  282.      * @param item 项
  283.      * @param by   要增加几(大于0)
  284.      * @return
  285.      */
  286.     public double hincr(String key, String item, double by) {
  287.         return redisTemplate.opsForHash().increment(key, item, by);
  288.     }
  289.     /**
  290.      * hash递减
  291.      *
  292.      * @param key  键
  293.      * @param item 项
  294.      * @param by   要减少记(小于0)
  295.      * @return
  296.      */
  297.     public double hdecr(String key, String item, double by) {
  298.         return redisTemplate.opsForHash().increment(key, item, -by);
  299.     }
  300.     //============================set=============================
  301.     /**
  302.      * 根据key获取Set中的所有值
  303.      *
  304.      * @param key 键
  305.      * @return
  306.      */
  307.     public Set<Object> sGet(String key) {
  308.         try {
  309.             return redisTemplate.opsForSet().members(key);
  310.         } catch (Exception e) {
  311.             e.printStackTrace();
  312.             return null;
  313.         }
  314.     }
  315.     /**
  316.      * 根据value从一个set中查询,是否存在
  317.      *
  318.      * @param key   键
  319.      * @param value 值
  320.      * @return true 存在 false不存在
  321.      */
  322.     public boolean sHasKey(String key, Object value) {
  323.         try {
  324.             return redisTemplate.opsForSet().isMember(key, value);
  325.         } catch (Exception e) {
  326.             e.printStackTrace();
  327.             return false;
  328.         }
  329.     }
  330.     /**
  331.      * 将数据放入set缓存
  332.      *
  333.      * @param key    键
  334.      * @param values 值 可以是多个
  335.      * @return 成功个数
  336.      */
  337.     public long sSet(String key, Object... values) {
  338.         try {
  339.             return redisTemplate.opsForSet().add(key, values);
  340.         } catch (Exception e) {
  341.             e.printStackTrace();
  342.             return 0;
  343.         }
  344.     }
  345.     /**
  346.      * 将set数据放入缓存
  347.      *
  348.      * @param key    键
  349.      * @param time   时间(秒)
  350.      * @param values 值 可以是多个
  351.      * @return 成功个数
  352.      */
  353.     public long sSetAndTime(String key, long time, Object... values) {
  354.         try {
  355.             Long count = redisTemplate.opsForSet().add(key, values);
  356.             if (time > 0) {
  357.                 expire(key, time);
  358.             }
  359.             return count;
  360.         } catch (Exception e) {
  361.             e.printStackTrace();
  362.             return 0;
  363.         }
  364.     }
  365.     /**
  366.      * 获取set缓存的长度
  367.      *
  368.      * @param key 键
  369.      * @return
  370.      */
  371.     public long sGetSetSize(String key) {
  372.         try {
  373.             return redisTemplate.opsForSet().size(key);
  374.         } catch (Exception e) {
  375.             e.printStackTrace();
  376.             return 0;
  377.         }
  378.     }
  379.     /**
  380.      * 移除值为value的
  381.      *
  382.      * @param key    键
  383.      * @param values 值 可以是多个
  384.      * @return 移除的个数
  385.      */
  386.     public long setRemove(String key, Object... values) {
  387.         try {
  388.             Long count = redisTemplate.opsForSet().remove(key, values);
  389.             return count;
  390.         } catch (Exception e) {
  391.             e.printStackTrace();
  392.             return 0;
  393.         }
  394.     }
  395.     //===============================list=================================
  396.     /**
  397.      * 获取list缓存的内容
  398.      *
  399.      * @param key   键
  400.      * @param start 开始
  401.      * @param end   结束  0 到 -1代表所有值
  402.      * @return
  403.      */
  404.     public List<Object> lGet(String key, long start, long end) {
  405.         try {
  406.             return redisTemplate.opsForList().range(key, start, end);
  407.         } catch (Exception e) {
  408.             e.printStackTrace();
  409.             return null;
  410.         }
  411.     }
  412.     /**
  413.      * 获取list缓存的长度
  414.      *
  415.      * @param key 键
  416.      * @return
  417.      */
  418.     public long lGetListSize(String key) {
  419.         try {
  420.             return redisTemplate.opsForList().size(key);
  421.         } catch (Exception e) {
  422.             e.printStackTrace();
  423.             return 0;
  424.         }
  425.     }
  426.     /**
  427.      * 通过索引 获取list中的值
  428.      *
  429.      * @param key   键
  430.      * @param index 索引  index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
  431.      * @return
  432.      */
  433.     public Object lGetIndex(String key, long index) {
  434.         try {
  435.             return redisTemplate.opsForList().index(key, index);
  436.         } catch (Exception e) {
  437.             e.printStackTrace();
  438.             return null;
  439.         }
  440.     }
  441.     /**
  442.      * 将list放入缓存
  443.      *
  444.      * @param key   键
  445.      * @param value 值
  446.      * @return
  447.      */
  448.     public boolean lSet(String key, Object value) {
  449.         try {
  450.             redisTemplate.opsForList().rightPush(key, value);
  451.             return true;
  452.         } catch (Exception e) {
  453.             e.printStackTrace();
  454.             return false;
  455.         }
  456.     }
  457.     /**
  458.      * 将list放入缓存
  459.      *
  460.      * @param key   键
  461.      * @param value 值
  462.      * @param time  时间(秒)
  463.      * @return
  464.      */
  465.     public boolean lSet(String key, Object value, long time) {
  466.         try {
  467.             redisTemplate.opsForList().rightPush(key, value);
  468.             if (time > 0) {
  469.                 expire(key, time);
  470.             }
  471.             return true;
  472.         } catch (Exception e) {
  473.             e.printStackTrace();
  474.             return false;
  475.         }
  476.     }
  477.     /**
  478.      * 将list放入缓存
  479.      *
  480.      * @param key   键
  481.      * @param value 值
  482.      * @return
  483.      */
  484.     public boolean lSet(String key, List<Object> value) {
  485.         try {
  486.             redisTemplate.opsForList().rightPushAll(key, value);
  487.             return true;
  488.         } catch (Exception e) {
  489.             e.printStackTrace();
  490.             return false;
  491.         }
  492.     }
  493.     /**
  494.      * 将list放入缓存
  495.      *
  496.      * @param key   键
  497.      * @param value 值
  498.      * @param time  时间(秒)
  499.      * @return
  500.      */
  501.     public boolean lSet(String key, List<Object> value, long time) {
  502.         try {
  503.             redisTemplate.opsForList().rightPushAll(key, value);
  504.             if (time > 0) {
  505.                 expire(key, time);
  506.             }
  507.             return true;
  508.         } catch (Exception e) {
  509.             e.printStackTrace();
  510.             return false;
  511.         }
  512.     }
  513.     /**
  514.      * 根据索引修改list中的某条数据
  515.      *
  516.      * @param key   键
  517.      * @param index 索引
  518.      * @param value 值
  519.      * @return
  520.      */
  521.     public boolean lUpdateIndex(String key, long index, Object value) {
  522.         try {
  523.             redisTemplate.opsForList().set(key, index, value);
  524.             return true;
  525.         } catch (Exception e) {
  526.             e.printStackTrace();
  527.             return false;
  528.         }
  529.     }
  530.     /**
  531.      * 移除N个值为value
  532.      *
  533.      * @param key   键
  534.      * @param count 移除多少个
  535.      * @param value 值
  536.      * @return 移除的个数
  537.      */
  538.     public long lRemove(String key, long count, Object value) {
  539.         try {
  540.             Long remove = redisTemplate.opsForList().remove(key, count, value);
  541.             return remove;
  542.         } catch (Exception e) {
  543.             e.printStackTrace();
  544.             return 0;
  545.         }
  546.     }
  547.     /**
  548.      * 模糊查询获取key值
  549.      *
  550.      * @param pattern
  551.      * @return
  552.      */
  553.     public Set keys(String pattern) {
  554.         return redisTemplate.keys(pattern);
  555.     }
  556.     /**
  557.      * 使用Redis的消息队列
  558.      *
  559.      * @param channel
  560.      * @param message 消息内容
  561.      */
  562.     public void convertAndSend(String channel, Object message) {
  563.         redisTemplate.convertAndSend(channel, message);
  564.     }
  565.     //=========BoundListOperations 用法 start============
  566.     /**
  567.      * 将数据添加到Redis的list中(从右边添加)
  568.      *
  569.      * @param listKey
  570.      * @param timeout 有效时间
  571.      * @param unit    时间类型
  572.      * @param values  待添加的数据
  573.      */
  574.     public void addToListRight(String listKey, long timeout, TimeUnit unit, Object... values) {
  575.         //绑定操作
  576.         BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
  577.         //插入数据
  578.         boundValueOperations.rightPushAll(values);
  579.         //设置过期时间
  580.         boundValueOperations.expire(timeout, unit);
  581.     }
  582.     /**
  583.      * 根据起始结束序号遍历Redis中的list
  584.      *
  585.      * @param listKey
  586.      * @param start   起始序号
  587.      * @param end     结束序号
  588.      * @return
  589.      */
  590.     public List<Object> rangeList(String listKey, long start, long end) {
  591.         //绑定操作
  592.         BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
  593.         //查询数据
  594.         return boundValueOperations.range(start, end);
  595.     }
  596.     /**
  597.      * 弹出右边的值 --- 并且移除这个值
  598.      *
  599.      * @param listKey
  600.      */
  601.     public Object rightPop(String listKey) {
  602.         //绑定操作
  603.         BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
  604.         return boundValueOperations.rightPop();
  605.     }
  606.     //=========BoundListOperations 用法 End============
  607. }
复制代码
4. 测试
  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class MyTest {
  4.     @Resource
  5.     private RedisUtil redisUtil;
  6.     @Resource
  7.     private RedisTemplate<String, Object> redisTemplate;
  8.     @Test
  9.     public void test_redis_util() {
  10.         boolean flag = redisUtil.set("key", "value");
  11.         String v = (String) redisUtil.get("key");
  12.         System.out.println("flag = " + flag + " v = " + v);
  13.     }
  14.     @Test
  15.     public void test_redisTemplate() {
  16.         ValueOperations<String, Object> ops = redisTemplate.opsForValue();
  17.         ops.set("k1", "v1");
  18.         System.out.println(ops.get("k1"));
  19.     }
  20. }   
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4