转载地址:https://blog.csdn.net/supersub000/article/details/80099990
现在公司项目使用的是SpringBoot框架,因为最近需要使用redis缓存,所以就需要写一个公共的redis工具类,发现其实SpringBoot对redis已经进行了封装,只需要加入redis的相关依赖就可以了。首先在pom.xml加入依赖:
-
<dependency>
-
<groupId>org.springframework.boot </groupId>
-
<artifactId>spring-boot-starter-data-redis </artifactId>
-
</dependency>
然后写redis配置类RedisConfiguration,需要注意的是在配置中一般需要配置redisTemplate的序列化方式,因为Spring redis的默认序列化方式是JDK序列化,所以缓存对象一般都要实现java.io.Serializable接口,不然在使用时会报错,而且在redis中读取内容时,除了属性信息外还会有很多其他信息,可读性较差。我这里使用的是GenericJackson2JsonRedisSerializer接口,相比Jackson2JsonRedisSerializer接口多了@class属性,类的全路径包名,方便反系列化。
-
import org.springframework.beans.factory.annotation.Autowired;
-
import org.springframework.beans.factory.annotation.Value;
-
import org.springframework.cache.CacheManager;
-
import org.springframework.cache.annotation.CachingConfigurerSupport;
-
import org.springframework.cache.annotation.EnableCaching;
-
import org.springframework.context.annotation.Bean;
-
import org.springframework.context.annotation.Configuration;
-
import org.springframework.data.redis.cache.RedisCacheManager;
-
import org.springframework.data.redis.connection.RedisConnectionFactory;
-
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
-
import org.springframework.data.redis.core.HashOperations;
-
import org.springframework.data.redis.core.RedisTemplate;
-
import org.springframework.data.redis.core.ValueOperations;
-
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
-
import org.springframework.data.redis.serializer.StringRedisSerializer;
-
import redis.clients.jedis.JedisPoolConfig;
-
-
/**
-
* redis配置
-
*
-
* @create 2018-04-24 下午9:38
-
**/
-
-
-
public class RedisConfiguration extends CachingConfigurerSupport {
-
"${redis.host}")(
-
private String host;
-
"${redis.port}")(
-
private Integer port;
-
"${redis.timeout}")(
-
private Integer timeout;
-
"${redis.maxTotal}")(
-
private Integer maxTotal;
-
"${redis.maxIdle}")(
-
private Integer maxIdle;
-
"${redis.maxWaitMillis}")(
-
private Long maxWaitMillis;
-
"${redis.testOnBorrow}")(
-
private Boolean testOnBorrow;
-
"${redis.database}")(
-
private Integer database;
-
-
-
/**
-
* 注入 RedisConnectionFactory
-
*/
-
-
RedisConnectionFactory redisConnectionFactory;
-
-
/**
-
* 缓存管理器.
-
*
-
* @param redisTemplate
-
* @return
-
*/
-
-
public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
-
CacheManager cacheManager = new RedisCacheManager(redisTemplate);
-
return cacheManager;
-
}
-
-
-
/**
-
* 配置redisTemplate
-
* <p>
-
* 通过redisConnectionFactory引入redis在配置文件中的连接配置
-
*/
-
-
public RedisTemplate<String, Object> redisTemplate() {
-
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
-
initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
-
redisTemplate.afterPropertiesSet();
-
return redisTemplate;
-
}
-
-
-
public RedisConnectionFactory redisConnectionFactory() {
-
JedisPoolConfig jedisPoolConfig = getJedisPoolConfig();
-
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
-
jedisConnectionFactory.setHostName(host);
-
jedisConnectionFactory.setPort(port);
-
jedisConnectionFactory.setDatabase(database);
-
jedisConnectionFactory.setUsePool( true);
-
jedisConnectionFactory.setPoolConfig(jedisPoolConfig);
-
return jedisConnectionFactory;
-
}
-
-
private JedisPoolConfig getJedisPoolConfig() {
-
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
-
//控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;
-
//如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
-
jedisPoolConfig.setMaxTotal(maxTotal);
-
//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
-
jedisPoolConfig.setMaxIdle(maxIdle);
-
//表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
-
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
-
//在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
-
jedisPoolConfig.setTestOnBorrow(testOnBorrow);
-
return jedisPoolConfig;
-
}
-
-
/**
-
* 设置数据存入 redis 的序列化方式
-
*
-
* @param redisTemplate
-
* @param factory
-
*/
-
private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
-
redisTemplate.setKeySerializer( new StringRedisSerializer());
-
redisTemplate.setHashKeySerializer( new StringRedisSerializer());
-
redisTemplate.setHashValueSerializer( new GenericJackson2JsonRedisSerializer());
-
redisTemplate.setValueSerializer( new GenericJackson2JsonRedisSerializer());
-
redisTemplate.setConnectionFactory(factory);
-
}
-
-
-
}
其中redisTemplate是Spring对Redis的相关操作的封装类,支持Redis的原生api,一般在定义RedisTemplate<K,V>,K的类型一般使用String,V的类型根据自己的业务需求进行定义,一般定义类型为Object,避免定义为RedisTemplate<Object,Object>。在RedisTemplate已经定义了对五种数据类型的操作:
-
redisTemplate.opsForValue(); //字符串操作
-
redisTemplate.opsForHash(); //hash操作
-
redisTemplate.opsForList(); //list操作
-
redisTemplate.opsForSet(); //set操作
-
redisTemplate.opsForZSet(); //有序set操作
每种操作都应对了的操作类,一般是Default开头,具体的源码还没有进行研究,本篇文章主要讲如何进行配置,更深的研究后续有时间会和小伙伴们进行分享。
Redis的相关配置后,就可以编写Redis的相关的工具类,一般命名RedisUtils或者RedisDao,下面是代码:
-
import org.springframework.data.redis.core.RedisTemplate;
-
import org.springframework.stereotype.Repository;
-
import javax.annotation.Resource;
-
import java.util.Date;
-
import java.util.HashMap;
-
import java.util.Set;
-
import java.util.concurrent.TimeUnit;
-
-
/**
-
* redis工具类
-
*
-
* @create 2018-04-24 下午9:41
-
**/
-
"redisDao")(
-
public class RedisDaoImpl implements RedisDao{
-
-
protected RedisTemplate<String,Object> redisTemplate;
-
-
/**
-
* 查询key,支持模糊查询
-
*
-
* @param key 传过来时key的前后端已经加入了*,或者根据具体处理
-
* */
-
-
public Set<String> keys(String key){
-
return redisTemplate.keys(key);
-
}
-
-
/**
-
* 重命名key
-
* */
-
-
public void renameKey(String key,String newKey){
-
redisTemplate.rename(key,newKey);
-
}
-
-
-
/**
-
*字符串添加信息
-
* @param key
-
* @param obj 可以是单个的值,也可以是任意类型的对象
-
* */
-
-
public void set(String key,Object obj){
-
redisTemplate.opsForValue().set(key,obj);
-
}
-
-
/**
-
*字符串添加信息
-
* @param key
-
* @param obj 可以是单个的值,也可以是任意类型的对象
-
* @param expire 设置失效时间
-
* */
-
-
public void set(String key,Object obj,long expire){
-
redisTemplate.opsForValue().set(key,obj,expire,TimeUnit.SECONDS);
-
}
-
-
/**
-
* 字符串获取值
-
* @param key
-
* */
-
-
public Object get(String key){
-
return redisTemplate.opsForValue().get(key);
-
}
-
-
/**
-
* 删出key
-
* 这里跟下边deleteKey()最底层实现都是一样的,应该可以通用
-
* @param key
-
* */
-
-
public void delete(String key){
-
redisTemplate.opsForValue().getOperations().delete(key);
-
}
-
-
/**
-
* 添加单个
-
*
-
* @param key key
-
* @param filed filed
-
* @param domain 对象
-
*/
-
-
public void hset(String key,String filed,Object domain){
-
redisTemplate.opsForHash().put(key, filed, domain);
-
}
-
-
-
/**
-
* 添加HashMap
-
*
-
* @param key key
-
* @param hm 要存入的hash表
-
*/
-
-
public void hmset(String key, HashMap<String,Object> hm){
-
redisTemplate.opsForHash().putAll(key,hm);
-
}
-
-
/**
-
* 查询key和field所确定的值
-
*
-
* @param key 查询的key
-
* @param field 查询的field
-
* @return HV
-
*/
-
-
public Object hget(String key,String field) {
-
return redisTemplate.opsForHash().get(key, field);
-
}
-
-
/**
-
* 查询该key下所有值
-
*
-
* @param key 查询的key
-
* @return Map<HK, HV>
-
*/
-
-
public Object hget(String key) {
-
return redisTemplate.opsForHash().entries(key);
-
}
-
-
/**
-
* 删除key下所有值
-
*
-
* @param key 查询的key
-
*/
-
-
public void deleteKey(String key) {
-
redisTemplate.opsForHash().getOperations().delete(key);
-
}
-
-
/**
-
* 判断key和field下是否有值
-
*
-
* @param key 判断的key
-
* @param field 判断的field
-
*/
-
-
public Boolean hasKey(String key,String field) {
-
return redisTemplate.opsForHash().hasKey(key,field);
-
}
-
-
/**
-
* 判断key下是否有值
-
*
-
* @param key 判断的key
-
*/
-
-
public Boolean hasKey(String key) {
-
return redisTemplate.opsForHash().getOperations().hasKey(key);
-
}
-
-
-
public Boolean expire(String key, long sec) {
-
return redisTemplate.expire(key,sec,TimeUnit.SECONDS);
-
}
-
-
-
public Boolean expireAt(String key, Date date) {
-
return redisTemplate.expireAt(key,date);
-
}
-
}