<!--springboot整合redis--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!-- redis 依赖commons-pool  --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId></dependency>

RedisConfig

package com.gblfy.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;/**** redis配置类**/
@Configuration
public class RedisConfig {@Bean@SuppressWarnings("all")public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();redisTemplate.setConnectionFactory(redisConnectionFactory);Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper objectMapper = new ObjectMapper();objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(objectMapper);StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();// key采用String的序列化方式redisTemplate.setKeySerializer(stringRedisSerializer);// hash的key也采用String的序列化方式redisTemplate.setHashKeySerializer(stringRedisSerializer);// valuevalue采用jackson序列化方式redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);// hash的value采用jackson序列化方式redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);redisTemplate.afterPropertiesSet();return redisTemplate;}
}

RedisUtils

package com.gblfy.utils;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;/*** Redis工具类** @author 共通组* @date 2019年2月25日*/
@Component
public final class RedisUtils {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;// =============================common============================/**** 指定缓存失效时间** @param key  键* @param time 时间(秒)* @return*/public boolean expire(String key, long time) {try {if (time > 0) {redisTemplate.expire(key, time, TimeUnit.SECONDS);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/**** 根据key 获取过期时间** @param key 键 不能为null* @return 时间(秒) 返回0代表为永久有效*/public long getExpire(String key) {return redisTemplate.getExpire(key, TimeUnit.SECONDS);}/**** 判断key是否存在** @param key 键* @return true 存在 false不存在*/public boolean hasKey(String key) {try {return redisTemplate.hasKey(key);} catch (Exception e) {e.printStackTrace();return false;}}/**** 删除缓存** @param key 可以传一个值 或多个*/@SuppressWarnings("unchecked")public void del(String... key) {if (key != null && key.length > 0) {if (key.length == 1) {redisTemplate.delete(key[0]);} else {redisTemplate.delete(CollectionUtils.arrayToList(key));}}}// ============================String=============================/**** 普通缓存获取** @param key 键* @return 值**/public Object get(String key) {return key == null ? null : redisTemplate.opsForValue().get(key);}/**** 普通缓存放入** @param key   键* @param value 值* @return true成功 false失败**/public boolean set(String key, Object value) {try {redisTemplate.opsForValue().set(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/**** 普通缓存放入并设置时间** @param key   键* @param value 值* @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期* @return true成功 false 失败**/public boolean set(String key, Object value, long time) {try {if (time > 0) {redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);} else {set(key, value);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/**** 递增** @param key   键* @param delta 要增加几(大于0)* @return**/public long incr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递增因子必须大于0");}return redisTemplate.opsForValue().increment(key, delta);}/**** 递减** @param key   键* @param delta 要减少几(小于0)* @return**/public long decr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递减因子必须大于0");}return redisTemplate.opsForValue().increment(key, -delta);}// ================================Map=================================/**** HashGet** @param key  键 不能为null* @param item 项 不能为null* @return 值**/public Object hget(String key, String item) {return redisTemplate.opsForHash().get(key, item);}/**** 获取hashKey对应的所有键值** @param key 键* @return 对应的多个键值**/public Map<Object, Object> hmget(String key) {return redisTemplate.opsForHash().entries(key);}/**** HashSet** @param key 键* @param map 对应多个键值* @return true 成功 false 失败**/public boolean hmset(String key, Map<String, Object> map) {try {redisTemplate.opsForHash().putAll(key, map);return true;} catch (Exception e) {e.printStackTrace();return false;}}/**** HashSet 并设置时间** @param key  键* @param map  对应多个键值* @param time 时间(秒)* @return true成功 false失败**/public boolean hmset(String key, Map<String, Object> map, long time) {try {redisTemplate.opsForHash().putAll(key, map);if (time > 0) {expire(key, time);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/**** 向一张hash表中放入数据,如果不存在将创建** @param key   键* @param item  项* @param value 值* @return true 成功 false失败**/public boolean hset(String key, String item, Object value) {try {redisTemplate.opsForHash().put(key, item, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/**** 向一张hash表中放入数据,如果不存在将创建** @param key   键* @param item  项* @param value 值* @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间* @return true 成功 false失败**/public boolean hset(String key, String item, Object value, long time) {try {redisTemplate.opsForHash().put(key, item, value);if (time > 0) {expire(key, time);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/**** 删除hash表中的值** @param key  键 不能为null* @param item 项 可以使多个 不能为null**/public void hdel(String key, Object... item) {redisTemplate.opsForHash().delete(key, item);}/**** 判断hash表中是否有该项的值** @param key  键 不能为null* @param item 项 不能为null* @return true 存在 false不存在**/public boolean hHasKey(String key, String item) {return redisTemplate.opsForHash().hasKey(key, item);}/**** hash递增 如果不存在,就会创建一个 并把新增后的值返回** @param key  键* @param item 项* @param by   要增加几(大于0)* @return**/public double hincr(String key, String item, double by) {return redisTemplate.opsForHash().increment(key, item, by);}/**** hash递减** @param key  键* @param item 项* @param by   要减少记(小于0)* @return**/public double hdecr(String key, String item, double by) {return redisTemplate.opsForHash().increment(key, item, -by);}// ============================set=============================/**** 根据key获取Set中的所有值** @param key 键* @return**/public Set<Object> sGet(String key) {try {return redisTemplate.opsForSet().members(key);} catch (Exception e) {e.printStackTrace();return null;}}/**** 根据value从一个set中查询,是否存在** @param key   键* @param value 值* @return true 存在 false不存在**/public boolean sHasKey(String key, Object value) {try {return redisTemplate.opsForSet().isMember(key, value);} catch (Exception e) {e.printStackTrace();return false;}}/**** 将数据放入set缓存** @param key    键* @param values 值 可以是多个* @return 成功个数**/public long sSet(String key, Object... values) {try {return redisTemplate.opsForSet().add(key, values);} catch (Exception e) {e.printStackTrace();return 0;}}/**** 将set数据放入缓存** @param key    键* @param time   时间(秒)* @param values 值 可以是多个* @return 成功个数**/public long sSetAndTime(String key, long time, Object... values) {try {Long count = redisTemplate.opsForSet().add(key, values);if (time > 0)expire(key, time);return count;} catch (Exception e) {e.printStackTrace();return 0;}}/**** 获取set缓存的长度** @param key 键* @return**/public long sGetSetSize(String key) {try {return redisTemplate.opsForSet().size(key);} catch (Exception e) {e.printStackTrace();return 0;}}/**** 移除值为value的** @param key    键* @param values 值 可以是多个* @return 移除的个数**/public long setRemove(String key, Object... values) {try {Long count = redisTemplate.opsForSet().remove(key, values);return count;} catch (Exception e) {e.printStackTrace();return 0;}}// ===============================list=================================/**** 获取list缓存的内容** @param key   键* @param start 开始* @param end   结束 0 到 -1代表所有值* @return**/public List<Object> lGet(String key, long start, long end) {try {return redisTemplate.opsForList().range(key, start, end);} catch (Exception e) {e.printStackTrace();return null;}}/**** 获取list缓存的长度** @param key 键* @return**/public long lGetListSize(String key) {try {return redisTemplate.opsForList().size(key);} catch (Exception e) {e.printStackTrace();return 0;}}/**** 通过索引 获取list中的值** @param key   键* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推* @return**/public Object lGetIndex(String key, long index) {try {return redisTemplate.opsForList().index(key, index);} catch (Exception e) {e.printStackTrace();return null;}}/**** 将list放入缓存** @param key   键* @param value 值* @param time  时间(秒)* @return**/public boolean lSet(String key, Object value) {try {redisTemplate.opsForList().rightPush(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/**** 将list放入缓存** @param key   键* @param value 值* @param time  时间(秒)* @return**/public boolean lSet(String key, Object value, long time) {try {redisTemplate.opsForList().rightPush(key, value);if (time > 0)expire(key, time);return true;} catch (Exception e) {e.printStackTrace();return false;}}/**** 将list放入缓存** @param key   键* @param value 值* @param time  时间(秒)* @return**/public boolean lSet(String key, List<Object> value) {try {redisTemplate.opsForList().rightPushAll(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/**** 将list放入缓存** @param key   键* @param value 值* @param time  时间(秒)* @return**/public boolean lSet(String key, List<Object> value, long time) {try {redisTemplate.opsForList().rightPushAll(key, value);if (time > 0)expire(key, time);return true;} catch (Exception e) {e.printStackTrace();return false;}}/**** 根据索引修改list中的某条数据** @param key   键* @param index 索引* @param value 值* @return**/public boolean lUpdateIndex(String key, long index, Object value) {try {redisTemplate.opsForList().set(key, index, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/**** 移除N个值为value** @param key   键* @param count 移除多少个* @param value 值* @return 移除的个数**/public long lRemove(String key, long count, Object value) {try {Long remove = redisTemplate.opsForList().remove(key, count, value);return remove;} catch (Exception e) {e.printStackTrace();return 0;}}
}

User

package com.gblfy.entity;import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;import java.io.Serializable;@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class User implements Serializable {private static final long serialVersionUID = 1L;private Long id;private String name;
}

application.yml 主配置

server:port: 80
spring:profiles:active: alone #默认激活单机

application-alone.yml 单机配置

spring:redis:host: 192.168.0.114port: 6379jedis:pool:### 连接池最大连接数(使用负值表示没有限制)max-active: 9### 连接池最大阻塞等待时间(使用负值表示没有限制)max-wait: -1### 连接池中的最大空闲连接max-idle: 9### 连接池中的最小空闲连接min-idle: 0### Redis数据库索引(默认为0)database: 0### 连接超时时间(毫秒)timeout: 60000password:

application-sentinel.yml 哨兵配置

##哨兵
spring:redis:sentinel:master: mymasternodes:- 192.168.0.114:26379- 192.168.0.114:26380- 192.168.0.114:26381jedis:pool:### 连接池最大连接数(使用负值表示没有限制)max-active: 9### 连接池最大阻塞等待时间(使用负值表示没有限制)max-wait: -1### 连接池中的最大空闲连接max-idle: 9### 连接池中的最小空闲连接min-idle: 0### 连接超时时间(毫秒)timeout: 60000password:

application-cluster.yml 集群配置

#集群
spring:redis:cluster:nodes:- 192.168.0.114:7001- 192.168.0.114:7002- 192.168.0.114:7003- 192.168.0.114:7004- 192.168.0.114:7005- 192.168.0.114:7006jedis:pool:### 连接池最大连接数(使用负值表示没有限制)max-active: 9### 连接池最大阻塞等待时间(使用负值表示没有限制)max-wait: -1### 连接池中的最大空闲连接max-idle: 9### 连接池中的最小空闲连接min-idle: 0### 连接超时时间(毫秒)timeout: 60000password:

单元测试

package com.gblfy;import com.gblfy.entity.User;
import com.gblfy.utils.RedisUtils;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class RedisApplicationTests {@Autowiredprivate RedisUtils redisUtils;@Testpublic void contextLoads() {System.out.println("测试单元测试是否可用!");}//测试 存key string
//            value string/*** 存储String类型 key value*/@Testpublic void testStr() {redisUtils.set("String1", "str");log.info("String1: {}", redisUtils.get("String1"));}/*** 指定key的过期时间*/@Testpublic void testStrExpTimeout() {redisUtils.set("String2", "str2", 60 * 2);log.info("String2: {}", redisUtils.get("String2"));}/*** map*/@Testpublic void testMap() {Map<String, Object> map = new HashMap<String, Object>();map.put("int1", 1);map.put("int2", 2);map.put("int3", 3);redisUtils.set("map1", map, 60 * 2);log.info("map1: {}", redisUtils.get("map1"));}/*** 存储对象+list*/@Testpublic void testmap() {User u = new User();u.setId(1l);u.setName("雨昕");redisUtils.set("u", u, 60 * 2);log.info("u: {}", new Gson().toJson(redisUtils.get("u")));User u1 = (User) redisUtils.get("u");log.info("u1: {}", u1);User u2 = new User();u2.setId(1l);u2.setName("雨泽");List<User> userList = new ArrayList<User>();userList.add(u);userList.add(u2);redisUtils.set("userList", userList, 60 * 2);log.info("userList: {}", new Gson().toJson(redisUtils.get("userList")));}//-----------------------------------------------------------------------------------@Testpublic void testHget() throws Exception {redisUtils.hset("testHget", "testHget", "testHget");Assert.assertEquals("testHget", redisUtils.hget("testHget", "testHget"));redisUtils.hset("testHgetKey", "testHget", "testHgetValue");Assert.assertEquals("testHgetValue", redisUtils.hget("testHgetKey", "testHget"));}@Testpublic void testHmget() throws Exception {redisUtils.hset("testHmget", "testHmget1", "testHmget1");redisUtils.hset("testHmget", "testHmget2", "testHmget2");Map<Object, Object> map = redisUtils.hmget("testHmget");if (MapUtils.isNotEmpty(map)) {for (Map.Entry<Object, Object> e : map.entrySet()) {System.err.println(e.getKey() + "===" + e.getValue());}}}/*** 设置缓存过期时间*/@Testpublic void testExpire() throws Exception {redisUtils.set("aaaKey", "aaaValue");redisUtils.expire("aaaKey", 10);Assert.assertEquals(redisUtils.get("aaaKey"), "aaaValue");TimeUnit.SECONDS.sleep(10);Assert.assertNotEquals(redisUtils.get("aaaKey"), "aaaValue");}@Testpublic void testGetExpire() throws Exception {redisUtils.set("aaaKey", "aaaValue");redisUtils.expire("aaaKey", 10);// 设置了缓存就会及时的生效,所以缓存时间小于最初设置的时间Assert.assertTrue(redisUtils.getExpire("aaaKey") < 10L);}@Testpublic void testHasKey() throws Exception {redisUtils.set("aaaKey", "aaaValue");// 存在的Assert.assertTrue(redisUtils.hasKey("aaaKey"));// 不存在的Assert.assertFalse(redisUtils.hasKey("bbbKey"));}@Testpublic void testDel() throws Exception {redisUtils.set("aaaKey", "aaaValue");// 存在的Assert.assertTrue(redisUtils.hasKey("aaaKey"));redisUtils.del("aaaKey");Assert.assertFalse(redisUtils.hasKey("bbbKey"));}
}

SpringBoot 整合Redis 单机、哨兵、集群相关推荐

  1. SpringBoot整合Redis(单机/哨兵/集群)

    pom <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http:// ...

  2. Redis sentinel哨兵集群

    Redis sentinel哨兵集群 sentinel(sen/te/nou) redis哨兵集群 作用:可以实现类似mysql的mha的相关操作,实时监控redis各个数据库的运行情况,并且在主库停 ...

  3. SpringBoot之单Redis与哨兵集群连接配置

    引入Redis依赖 <!-- 指定SpringBoot版本 --><parent><groupId>org.springframework.boot</gro ...

  4. redis 主从 哨兵 集群 及原理

    1.主从哨兵 1.主从哨兵架构图: 此图为最常见的一主两从结构,一个master主机,两个slave主机.每台主机上都运行着两个进程: redis-server 服务,处理redis正常的数据操作与响 ...

  5. redis 主从 哨兵 集群部署

    介绍 Redis是当前比较热门的NOSQL系统之一,它是一个key-value存储系统.和Memcache类似,但很大程度补偿了Memcache的不足,它支持存储的value类型相对更多,包括stri ...

  6. Redis面试 - 哨兵集群实现高可用

    Redis 哨兵集群实现高可用 哨兵的介绍 sentinel,中文名是哨兵.哨兵是 redis 集群机构中非常重要的一个组件,主要有以下功能: 集群监控:负责监控 redis master 和 sla ...

  7. Redis:哨兵集群

    目录 基于pub/sub 机制的哨兵集群组成 基于pub/sub 机制的客户端事件通知 由哪个哨兵执行主从切换 哨兵实例是不是越多越好,如果同时调大 down-after-milliseconds 值 ...

  8. Redis主从哨兵集群模式概念以及搭建

    目录 前言 一.Redis使用准备工作 1.1.下载redis 1.2.安装redis 二.Redis部署 2.1.单节点模式部署 2.2.主从模式部署 2.2.1 主从模式的感念: 2.2.2 主从 ...

  9. Redis学习笔记之Redis单机,伪集群,Sentinel主从复制的安装和配置

    0x00 Redis简介 Redis是一款开源的.高性能的键-值存储(key-value store).它常被称作是一款数据结构服务器(data structure server). Redis的键值 ...

最新文章

  1. oracle的存储过程调试,oracle 运行普通方式及调试debug方式存储过程性能区别
  2. 一位群友作为后端开发在滴滴和头条分别干了 2 年的经验总结
  3. Column 'Status' in where clause is ambiguous
  4. 初识Typescript及vscode环境配置
  5. 技术支持工程师自测评估下载
  6. LeetCode 1717. 删除子字符串的最大得分
  7. 使用webpack5模块联邦
  8. 【安全牛学习笔记】Kali Linux***测试介绍
  9. 三十一、K8s供应链安全2 - 镜像的检测及优化与yaml文件安全
  10. php 多个files 数量,php – 具有多个字段时$_FILES数组的奇怪格式
  11. Windows All 系统下载
  12. 学会Java输入输出流,看这一篇就够了,建议收藏!
  13. 解决Win7 64位安装 Microsoft .NET Framework 4 失败的情况
  14. laypage分页java例子_laypage分页控件使用实例详解
  15. linux系统发育树的构建步骤,使用modeltest-ng和raxml-ng构建ML系统发育树
  16. 数据交换技术(*):电路交换,报文交换,分组交换的概念,特点和优缺点以及存储转发技术概念
  17. ubuntu命令行查看dns_Dog-用于DNS查询的命令行工具
  18. 筱筱看博客(git 冲突解决)
  19. 微信jssdk签名生成代码示例PHP版本
  20. 阿里云DNS服务器免费版和付费版列表

热门文章

  1. 这些行为,属于学术不端!
  2. c++堆栈中 top() pop()的具体作用是什么
  3. c++ List(双向链表)
  4. 性能提升一倍,云原生网关支持 TLS 硬件加速
  5. 万级规模 K8s 如何管理?蚂蚁双11核心技术公开
  6. 不要低估AI面临的困境
  7. 对话阿里云Alex Chen:下一代存储应如何面对云转型?
  8. 生物智能与AI——关乎创造、关乎理解(上)
  9. 万物互联下的碎片化怎么破?UINO优锘推出物联网产业元宇宙“物联森友会”
  10. 一部手机是否能用 7 年?苹果、三星、Google:三年差不多!