官方文檔地址: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()