官方文档地址:https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#why-spring-redis
环境 Springboot 2.1.0.RELEASE
1、添加jar包:
<!--对redis的支持--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
spring-boot-starter-data-redis中包含的依赖:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.1.0.RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>2.1.2.RELEASE</version> <scope>compile</scope> <exclusions> <exclusion> <artifactId>jcl-over-slf4j</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> <version>5.1.2.RELEASE</version> <scope>compile</scope> </dependency> </dependencies>
2、Spring默认为我们注入了RedisTemplate和StringRedisTemplate ,如果我们没有手动注入相同名字的bean的话
RedisTemplate默认的key,value,hashKey,hashValue序列化方式都为JdkSerializationRedisSerializer,即二进制序列化方式
StringRedisTemplate 所有的序列化方式都为RedisSerializer.string(),即String
@Configuration @ConditionalOnClass(RedisOperations.class) @EnableConfigurationProperties(RedisProperties.class) @Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class }) public class RedisAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "redisTemplate") public RedisTemplate<Object, Object> redisTemplate( RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); return template; } @Bean @ConditionalOnMissingBean public StringRedisTemplate stringRedisTemplate( RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { StringRedisTemplate template = new StringRedisTemplate(); template.setConnectionFactory(redisConnectionFactory); return template; } }
Springboot 2.1.0.RELEASE 默认的Redis客户端为 Lettuce,默认的连接工厂为LettuceConnectionFactory:
@Bean @ConditionalOnMissingBean(RedisConnectionFactory.class) public LettuceConnectionFactory redisConnectionFactory( ClientResources clientResources) throws UnknownHostException { LettuceClientConfiguration clientConfig = getLettuceClientConfiguration( clientResources, this.properties.getLettuce().getPool()); return createLettuceConnectionFactory(clientConfig); }
另外,Spring Data Redis提供了如下的ConnectionFactory:
JedisConnectionFactory | 使用Jedis作为Redis的客户端 |
JredisConnectionFactory | 使用Jredis作为Redis的客户端 |
LettuceConnectionFactory | 使用Letture作为Redis的客户端 |
SrpConnectionFactory |
使用Spullara/redis-protocol作为Redis的客户端 |
3、spring-data-redis提供的序列化方式:
对于字符串,我们希望key,value序列化方式都为String,但是对于Hash,key的序列化方式为String,但是value的序列化方式
我们希望为JSON。所以我们需要自己配置RedisTemplate并注入到Spring容器中:
一、单点方案:
4、自定义配置RedisTemple
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.RedisSerializer; /** * Redis配置类 * * @author yangyongjie * @date 2019/10/29 * @desc */ @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); // 序列化方式全部为String redisTemplate.setKeySerializer(RedisSerializer.string()); redisTemplate.setValueSerializer(RedisSerializer.string()); redisTemplate.setHashKeySerializer(RedisSerializer.string()); // hash value序列化方式为JSON Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); return redisTemplate; } }
4、application.properties中配置Redis连接信息
#Redis相关配置 # Redis服务器地址 spring.redis.host=${redis.host} # Redis服务器连接端口 spring.redis.port=${redis.port} # 连接池最大连接数(使用负值表示没有限制) spring.redis.lettuce.pool.max-active=${redis.lettuce.pool.max-active} # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.lettuce.pool.max-wait=${redis.lettuce.pool.max-wait} # 连接池中的最大空闲连接 spring.redis.lettuce.pool.max-idle=${redis.lettuce.pool.max-idle} # 连接池中的最小空闲连接 spring.redis.lettuce.pool.min-idle=${redis.lettuce.pool.min-idle} # 连接超时时间(毫秒) spring.redis.timeout=${redis.timeout}
这里的配置最终会加载到RedisProperties中。
RedisProperties:
@ConfigurationProperties(prefix = "spring.redis") public class RedisProperties { private int database = 0; // Database index used by the connection factory private String url; // 连接URL,重写host,post和password,忽略用户名,如:redis://user:password@example.com:6379 private String host = "localhost"; // Redis server host private String password; // Login password of the redis server private int port = 6379; // Redis server port. private boolean ssl; // Whether to enable SSL support. private Duration timeout; //Connection timeout. private Sentinel sentinel; private Cluster cluster; private final Jedis jedis = new Jedis(); private final Lettuce lettuce = new Lettuce(); // getter and setter... public static class Pool { // 连接池配置属性 private int maxIdle = 8; // 连接池内空闲连接的最大数量,使用负值表示没有限制 private int minIdle = 0; // 连接池内维护的最小空闲连接数,值为正时才有效 private int maxActive = 8; // 给定时间连接池内最大连接数,使用负值表示没有限制 private Duration maxWait = Duration.ofMillis(-1); // 当池耗尽时,在抛出异常之前,连接分配应阻塞的最长时间。使用负值可无限期阻止 // getter and setter... } // Cluster properties. public static class Cluster { private List<String> nodes; // 逗号分隔的"host:port"列表,至少要有一个 private Integer maxRedirects; // 在集群中执行命令时要遵循的最大重定向数
// getter and setter... } // Redis sentinel properties. public static class Sentinel { private String master; // Name of the Redis server. private List<String> nodes; // Comma-separated list of "host:port" pairs. // getter and setter... } // Jedis client properties. public static class Jedis { private Pool pool; // Jedis pool configuration. // getter and setter... } // Lettuce client properties. public static class Lettuce { private Duration shutdownTimeout = Duration.ofMillis(100); // Shutdown timeout. private Pool pool; // Lettuce pool configuration. // getter and setter... } }
5、Redis工具类
主要的数据访问方法:
opsForValue() | 操作只有简单属性的数据 |
opsForList() | 操作含有list的数据 |
opsForSet() | 操作含有set的数据 |
opsForZSet() | 操作含有ZSet(有序集合)的数据 |
opsForHash() | 操作含有hash的数据 |
RedisUtil:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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 yangyongjie * @date 2019/10/11 * @desc */ @Component public class RedisUtil { private static final Logger LOGGER = LoggerFactory.getLogger(RedisUtil.class); // @Autowired // private RedisTemplate<Object, Object> redisTemplate; @Autowired private 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) { LOGGER.error("获取key的失效时间异常" + e.getMessage(), e); 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) { LOGGER.error("判断key是否存在异常" + e.getMessage(), e); return false; } } /** * 删除缓存 * * @param key 可以传一个值 或多个 */ 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) { LOGGER.error("设置String类型异常" + e.getMessage(), e); 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) { LOGGER.error("设置String类型及有效期异常" + e.getMessage(), e); 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) { LOGGER.error("批量设置Map类型异常" + e.getMessage(), e); 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) { LOGGER.error("批量设置Map类型及有效期异常" + e.getMessage(), e); 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) { LOGGER.error("设置单个哈希表异常" + e.getMessage(), e); 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) { LOGGER.error("设置单个哈希表及有效期异常" + e.getMessage(), e); 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); } /** * 269 * 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) { LOGGER.error("获取set异常" + e.getMessage(), e); 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) { LOGGER.error("获取set中是否存在某个值异常" + e.getMessage(), e); return false; } } /** * 321 * 将数据放入set缓存 * 322 * * @param key 键 * 323 * @param values 值 可以是多个 * 324 * @return 成功个数 * 325 */ public long sSet(String key, Object... values) { try { return redisTemplate.opsForSet().add(key, values); } catch (Exception e) { LOGGER.error("设置set异常" + e.getMessage(), e); 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) { LOGGER.error("设置set及有效期异常" + e.getMessage(), e); return 0; } } /** * 获取set缓存的长度 * * @param key 键 * @return */ public long sGetSetSize(String key) { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { LOGGER.error("获取set的长度异常" + e.getMessage(), e); 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) { LOGGER.error("移除set中某个值异常" + e.getMessage(), e); 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) { LOGGER.error("获取list异常" + e.getMessage(), e); return null; } } /** * 获取list缓存的长度 * * @param key 键 * @return */ public long lGetListSize(String key) { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { LOGGER.error("获取list长度异常" + e.getMessage(), e); 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) { LOGGER.error("通过索引获取list中的值异常" + e.getMessage(), e); return null; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, Object value) { try { redisTemplate.opsForList().rightPush(key, value); return true; } catch (Exception e) { LOGGER.error("设置list异常" + e.getMessage(), e); 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) { LOGGER.error("设置list及有效期异常" + e.getMessage(), e); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, List<Object> value) { try { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { LOGGER.error("批量设置list异常" + e.getMessage(), e); 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) { LOGGER.error("批量设置list及有效期异常" + e.getMessage(), e); 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) { LOGGER.error("根据索引修改list中的某条数据异常" + e.getMessage(), e); 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) { LOGGER.error("移除list中N个值为value异常" + e.getMessage(), e); return 0; } } }
6、注入RedisUtil 依赖即可使用
@Autowired private RedisUtil redisUtil;
7、但是在每个使用RedisUtil的类里都要注入RedisUtil依赖很麻烦,RedisUtil也失去了工具类的基本性质。于是,不降RedisUtil作为一个bean注入到Spring容器中,至于怎么在RedisUtil中注入RedisTemplate<String, Object>属性,采用在第三方专门初始化bean的类中,从spring容器中获取 name 为 redisTemplate的bean,然后赋值,代码如下:
import com.xxx.common.utils.RedisUtil; import com.xxx.common.utils.ZKListenerUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.env.Environment; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; /** * 获取 application.properties中配置的属性 * * @author yangyongjie * @date 2019/9/25 * @desc */ @Component public class CustomPropertyConfig implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) { context = applicationContext; } /** * 获取配置的属性 * * @param key * @return */ public static String getproperties(String key) { if (StringUtils.isEmpty(key)) { return null; } Environment environment = context.getEnvironment(); return environment.getProperty(key); } /** * 初始化ZK配置的属性 */ @PostConstruct public void initZKConfig() { ZKListenerUtil.loadZKConfig(); } /** * 初始化redisTemplate */ @PostConstruct public void initRedisTemplate() { RedisUtil.setRedisTemplate((RedisTemplate<String, Object>) context.getBean("redisTemplate")); } }
RedisUtil工具类的方法全部设为静态方法,这样直接在代码中使用RedisUtil.xxx调用即可,不需要注入依赖:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.util.CollectionUtils; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Redis工具类 * * @author yangyongjie * @date 2019/10/11 * @desc */ public class RedisUtil { private RedisUtil() { } private static final Logger LOGGER = LoggerFactory.getLogger(RedisUtil.class); // @Autowired // private RedisTemplate<Object, Object> redisTemplate; private static RedisTemplate<String, Object> redisTemplate; public static void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) { RedisUtil.redisTemplate = redisTemplate; } // =============================common============================ /** * 指定缓存失效时间 * * @param key 键 * @param time 时间(秒) * @return */ public static boolean expire(String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { LOGGER.error("获取key的失效时间异常" + e.getMessage(), e); return false; } } /** * 根据key 获取过期时间 * * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效 */ public static long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * 判断key是否存在 * * @param key 键 * @return true 存在 false不存在 */ public static boolean hasKey(String key) { try { return redisTemplate.hasKey(key); } catch (Exception e) { LOGGER.error("判断key是否存在异常" + e.getMessage(), e); return false; } } /** * 删除缓存 * * @param key 可以传一个值 或多个 */ public static 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 static String get(String key) { if (key == null) { return null; } Object value = redisTemplate.opsForValue().get(key); return value == null ? null : String.valueOf(value); } /** * 普通缓存放入 * * @param key 键 * @param value 值 * @return true成功 false失败 */ public static boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { LOGGER.error("设置String类型异常" + e.getMessage(), e); return false; } } /** * 普通缓存放入并设置时间 * * @param key 键 * @param value 值 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 * @return true成功 false 失败 */ public static 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) { LOGGER.error("设置String类型及有效期异常" + e.getMessage(), e); return false; } } /** * 递增 1 * * @param key 键 * @return */ public static long incr(String key) { return redisTemplate.opsForValue().increment(key); } /** * 递增 * * @param key 键 * @param delta 要增加几(大于0) * @return */ public static long incr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递增因子必须大于0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * 递减 1 * * @param key 键 * @return */ public static long decr(String key) { return redisTemplate.opsForValue().decrement(key); } /** * 递减 * * @param key 键 * @param delta 要减少几(小于0) * @return */ public static long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().decrement(key, delta); } // ================================Map================================= /** * HashGet * * @param key 键 不能为null * @param item 项 不能为null * @return 值 */ public static Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * 获取hashKey对应的所有键值 * * @param key 键 * @return 对应的多个键值 */ public static Map<Object, Object> hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * HashSet * * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 */ public static boolean hmset(String key, Map<String, Object> map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { LOGGER.error("批量设置Map类型异常" + e.getMessage(), e); return false; } } /** * HashSet 并设置时间 * * @param key 键 * @param map 对应多个键值 * @param time 时间(秒) * @return true成功 false失败 */ public static 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) { LOGGER.error("批量设置Map类型及有效期异常" + e.getMessage(), e); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * * @param key 键 * @param item 项 * @param value 值 * @return true 成功 false失败 */ public static boolean hset(String key, String item, Object value) { try { redisTemplate.opsForHash().put(key, item, value); return true; } catch (Exception e) { LOGGER.error("设置单个哈希表异常" + e.getMessage(), e); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * * @param key 键 * @param item 项 * @param value 值 * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 * @return true 成功 false失败 */ public static 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) { LOGGER.error("设置单个哈希表及有效期异常" + e.getMessage(), e); return false; } } /** * 删除hash表中的值 * * @param key 键 不能为null * @param item 项 可以使多个 不能为null */ public static void hdel(String key, Object... item) { redisTemplate.opsForHash().delete(key, item); } /** * 判断hash表中是否有该项的值 * * @param key 键 不能为null * @param item 项 不能为null * @return true 存在 false不存在 */ public static boolean hHasKey(String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); } /** * 269 * hash递增 如果不存在,就会创建一个 并把新增后的值返回 * * @param key 键 * @param item 项 * @param by 要增加几(大于0) * @return */ public static 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 static double hdecr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, -by); } // ============================set============================= /** * 根据key获取Set中的所有值 * * @param key 键 * @return */ public static Set<Object> sGet(String key) { try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { LOGGER.error("获取set异常" + e.getMessage(), e); return null; } } /** * 根据value从一个set中查询,是否存在 * * @param key 键 * @param value 值 * @return true 存在 false不存在 */ public static boolean sHasKey(String key, Object value) { try { return redisTemplate.opsForSet().isMember(key, value); } catch (Exception e) { LOGGER.error("获取set中是否存在某个值异常" + e.getMessage(), e); return false; } } /** * 321 * 将数据放入set缓存 * 322 * * @param key 键 * 323 * @param values 值 可以是多个 * 324 * @return 成功个数 * 325 */ public static long sSet(String key, Object... values) { try { return redisTemplate.opsForSet().add(key, values); } catch (Exception e) { LOGGER.error("设置set异常" + e.getMessage(), e); return 0; } } /** * 将set数据放入缓存 * * @param key 键 * @param time 时间(秒) * @param values 值 可以是多个 * @return 成功个数 */ public static 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) { LOGGER.error("设置set及有效期异常" + e.getMessage(), e); return 0; } } /** * 获取set缓存的长度 * * @param key 键 * @return */ public static long sGetSetSize(String key) { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { LOGGER.error("获取set的长度异常" + e.getMessage(), e); return 0; } } /** * 移除值为value的 * * @param key 键 * @param values 值 可以是多个 * @return 移除的个数 */ public static long setRemove(String key, Object... values) { try { Long count = redisTemplate.opsForSet().remove(key, values); return count; } catch (Exception e) { LOGGER.error("移除set中某个值异常" + e.getMessage(), e); return 0; } } // ===============================list================================= /** * 获取list缓存的内容 * * @param key 键 * @param start 开始 * @param end 结束 0 到 -1代表所有值 * @return */ public static List<Object> lGet(String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { LOGGER.error("获取list异常" + e.getMessage(), e); return null; } } /** * 获取list缓存的长度 * * @param key 键 * @return */ public static long lGetListSize(String key) { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { LOGGER.error("获取list长度异常" + e.getMessage(), e); return 0; } } /** * 通过索引 获取list中的值 * * @param key 键 * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推 * @return */ public static Object lGetIndex(String key, long index) { try { return redisTemplate.opsForList().index(key, index); } catch (Exception e) { LOGGER.error("通过索引获取list中的值异常" + e.getMessage(), e); return null; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @return */ public static boolean lSet(String key, Object value) { try { redisTemplate.opsForList().rightPush(key, value); return true; } catch (Exception e) { LOGGER.error("设置list异常" + e.getMessage(), e); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public static 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) { LOGGER.error("设置list及有效期异常" + e.getMessage(), e); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @return */ public static boolean lSet(String key, List<Object> value) { try { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { LOGGER.error("批量设置list异常" + e.getMessage(), e); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public static 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) { LOGGER.error("批量设置list及有效期异常" + e.getMessage(), e); return false; } } /** * 根据索引修改list中的某条数据 * * @param key 键 * @param index 索引 * @param value 值 * @return */ public static boolean lUpdateIndex(String key, long index, Object value) { try { redisTemplate.opsForList().set(key, index, value); return true; } catch (Exception e) { LOGGER.error("根据索引修改list中的某条数据异常" + e.getMessage(), e); return false; } } /** * 移除N个值为value * * @param key 键 * @param count 移除多少个 * @param value 值 * @return 移除的个数 */ public static long lRemove(String key, long count, Object value) { try { Long remove = redisTemplate.opsForList().remove(key, count, value); return remove; } catch (Exception e) { LOGGER.error("移除list中N个值为value异常" + e.getMessage(), e); return 0; } } }
redis分布式锁方法:
// ===============================lock================================= /** * set值当其key不存在时 * * @param key * @param value * @return */ public static Boolean setnx(String key, Object value) { return redisTemplate.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { try { byte[] keyBys = redisTemplate.getStringSerializer().serialize(key); byte[] valBys = redisTemplate.getStringSerializer().serialize(String.valueOf(value)); return connection.setNX(keyBys, valBys); } finally { connection.close(); } } }); } /** * set值当key不存在时并设置有效期 * * @param key * @param value * @param seconds */ public static Boolean setex(String key, Object value, long seconds) { return redisTemplate.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { try { byte[] keyBys = redisTemplate.getStringSerializer().serialize(key); byte[] valBys = redisTemplate.getStringSerializer().serialize(String.valueOf(value)); return connection.setEx(keyBys, seconds, valBys); } finally { connection.close(); } } }); }
同redisTemplate.opsForValue().setIfAbsent()
二、Cluster 集群方案
方式1、在上述的基础之上,在application.properties中配置集群信息:
# 集群信息,host:port,多个之间以逗号分隔
spring.redis.cluster.nodes=host:port,host:port
此方式依赖Springboot提供的RedisAutoConfiguration类上Import的LettuceConnectionConfiguration来实现的。
方式2、在Springboot的application.properties中配置集群信息,然后手动创建RedisConnectionFactory 。
但是这种方式不能配置 连接池等其他信息。
@Component @ConfigurationProperties(prefix = "spring.redis.cluster") public class ClusterConfigurationProperties { /* * spring.redis.cluster.nodes[0] = 127.0.0.1:7379 * spring.redis.cluster.nodes[1] = 127.0.0.1:7380 * ... */ List<String> nodes; // getter and setter } @Configuration public class AppConfig { /** * Type safe representation of application.properties */ @Autowired
ClusterConfigurationProperties clusterProperties; public @Bean RedisConnectionFactory connectionFactory() { return new LettuceConnectionFactory( new RedisClusterConfiguration(clusterProperties.getNodes())); } }
补充:若要配置连接池信息,又不想使用自动配置,想手动配置RedisConnectionFactory ,可以参考LettuceConnectionConfiguration的代码,使用LettuceConnectionFactory的如下构造器
LettuceConnectionFactory(RedisClusterConfiguration clusterConfiguration,LettuceClientConfiguration clientConfig)
三、哨兵方案
Spring Data Redis通过使用RedisSentinelConfiguration来支持哨兵模式
如:
/** * Jedis */ @Bean public RedisConnectionFactory jedisConnectionFactory() { RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration() .master("mymaster") .sentinel("127.0.0.1", 26379) .sentinel("127.0.0.1", 26380); return new JedisConnectionFactory(sentinelConfig); } /** * Lettuce */ @Bean public RedisConnectionFactory lettuceConnectionFactory() { RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration() .master("mymaster") .sentinel("127.0.0.1", 26379) .sentinel("127.0.0.1", 26380); return new LettuceConnectionFactory(sentinelConfig); }
或者直接在SpringBoot的application.properties中定义:
spring.redis.sentinel.master: name of the master node.
spring.redis.sentinel.nodes: Comma delimited list of host:port pairs.
spring.redis.sentinel.password: The password to apply when authenticating with Redis Sentinel
通过使用下面方式访问第一个活动的Sentinel
RedisConnectionFactory.getSentinelConnection() or RedisConnection.getSentinelCommands()