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.core.RedisTemplate;
@Configuration
@EnableCaching//开启注解
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}
}
这redis的工具类,主要用于对redis的操作方法封装,方便使用
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
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 org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* RedisAPI
*
* @author liuhui
* @date 2018-1-10
*/
@Component
public class RedisUtils {
private Logger logger = LoggerFactory.getLogger(RedisUtils.class);
@Resource
private RedisTemplate redisTemplate;
/**
* set key and value to redis
*
* @param key
* @param value
* @return
*/
public boolean set(String key, String value) {
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置序列化Value的实例化对象
redisTemplate.setValueSerializer(new StringRedisSerializer());
ValueOperations vo = redisTemplate.opsForValue();
vo.set(key, value);
return true;
}
/**
* set key and value to redis
*
* @param key
* @param seconds 有效期
* @param value
* @return
*/
public boolean set(String key, long seconds, String value) {
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置序列化Value的实例化对象
redisTemplate.setValueSerializer(new StringRedisSerializer());
ValueOperations vo = redisTemplate.opsForValue();
vo.set(key, value);
expire(key, seconds);
return true;
}
/**
* 更新指定key的value,剩余过期时间不变
* @param key
* @param value
* @return
*/
public boolean update(String key, String value) {
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置序列化Value的实例化对象
redisTemplate.setValueSerializer(new StringRedisSerializer());
ValueOperations vo = redisTemplate.opsForValue();
//获取当前key的过期时间
Long expireTime = redisTemplate.getExpire(key);
//重新设置设置过期时间
if (expireTime == null)
return false;
if (expireTime == -2 || expireTime == 0)
return false;
vo.set(key, value);
if (expireTime > 0)
expire(key, expireTime);
return true;
}
/**
* 获取剩余过期时间
* @param key
* @return
*/
public Long getExpire(String key) {
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置序列化Value的实例化对象
redisTemplate.setValueSerializer(new StringRedisSerializer());
ValueOperations vo = redisTemplate.opsForValue();
//获取当前key的过期时间
return redisTemplate.getExpire(key);
}
/**
* 判断某个key是否存在
*
* @param key
* @return
*/
public boolean exist(String key) {
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置序列化Value的实例化对象
redisTemplate.setValueSerializer(new StringRedisSerializer());
ValueOperations vo = redisTemplate.opsForValue();
Object value = vo.get(key);
return EmptyUtils.isEmpty(value) ? false : true;
}
public Object get(String key) {
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置序列化Value的实例化对象
redisTemplate.setValueSerializer(new StringRedisSerializer());
ValueOperations vo = redisTemplate.opsForValue();
return vo.get(key);
}
public void delete(String key) {
try {
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置序列化Value的实例化对象
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.delete(key);
} catch (Exception e) {
e.printStackTrace();
}
}
public Boolean setnx(final String key, final String value) throws Exception {
return redisTemplate.execute(new RedisCallback() {
@Override
public Boolean doInRedis(RedisConnection redisConnection) {
boolean flag = false;
try {
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置序列化Value的实例化对象
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
byte keys[] = stringRedisSerializer.serialize(key);
byte values[] = stringRedisSerializer.serialize(value);
flag = redisConnection.setNX(keys, values);
} catch (Exception e) {
e.printStackTrace();
} finally {
return flag;
}
}
});
}
public Boolean expire(final String key, final long expireTime) {
return redisTemplate.execute(new RedisCallback() {
@Override
public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
boolean flag = false;
try {
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置序列化Value的实例化对象
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
byte keys[] = stringRedisSerializer.serialize(key);
flag = redisConnection.expire(keys, expireTime);
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
});
}
public boolean lock(String key) {
boolean flag = false;
try {
String lockKey = generateLockKey(key);
flag = setnx(lockKey, "lock");
if (flag) {
System.out.println(expire(lockKey, Constants.Redis_Expire.DEFAULT_EXPIRE));
}
return flag;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
public Object getValueNx(String key) {
String lockKey = generateLockKey(key);
Object object = get(lockKey);
return object;
}
public void unlock(String key) {
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置序列化Value的实例化对象
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
String lockKey = generateLockKey(key);
RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
connection.del(lockKey.getBytes());
connection.close();
}
private String generateLockKey(String key) {
return String.format("LOCK:%s", key);
}
public boolean validate(String token) {
return exist(token);
}
}
这是一些简单的使用,获取,生成,更新token
@Autowired
private RedisUtils redisUtils;
@PostMapping("/setToken")
@ApiOperation(value = "设置token")
public String setToken(String token){
/*设置生成有效期*/
long time = 60;
boolean falge = redisUtils.set("token",time, token);
return falge ? "redis测试成功":"redis测试失败";
}
@PostMapping("/getToken")
@ApiOperation(value = "获取token")
public String getToken(String token){
Long expire = redisUtils.getExpire(token); /*获取有效时间*/
return redisUtils.get(token).toString()+"剩余有效时间为:"+expire.toString();
}
@PostMapping("/updateToken")
@ApiOperation(value = "更新token")
public String updateToken(String token,String value){
if(redisUtils.exist(token)){
Long expire1 = redisUtils.getExpire(token);
if(expire1 >= 10){
return "token不允许更新";
}
String newToken = "newToken";
redisUtils.set(token,30L,value); /*设置旧token的过期时间*/
redisUtils.set(newToken,120L,value); /*设置新token的过期时间*/
return newToken; /*将新的token返回给前台,前台将新的token进行放入请求同头中*/
}
Long expire = redisUtils.getExpire(token); /*获取有效时间*/
return redisUtils.get(token).toString()+"剩余有效时间为:"+expire.toString();
}
到这里就结束了,希望对大家有所帮助。如有不对,欢迎指正!