还是使用上次的工程
pom.xml中引入依赖
<!-- redis组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application.yml新增配置
spring:
redis:
open: false # 是否开启redis缓存 true开启 false关闭
database: 0 #redis默认有16个库
host: 127.0.0.1
port: 6379
password:
timeout: 6000
pool:
max-active: 20 # 连接池最大连接数(使用负值表示没有限制)
max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 10 # 连接池中的最大空闲连接
min-idle: 5 # 连接池中的最小空闲连接
启动redis服务 默认端口6379
创建RedisConfig配置类
package com.xiaohan.bootdemo.config;
import org.springframework.beans.factory.annotation.Autowired;
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.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Autowired
private RedisConnectionFactory factory;
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
// serializer策略
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}
// 简单K-V操作
@Bean
public ValueOperations<String,String> valueOperations(RedisTemplate<String, String> redisTemplate){
return redisTemplate.opsForValue();
}
}
因为存储的为key-value形式 需要对实体进行json转换操作
所以这里先创建一个Jackson工具类
将null值替换为空字符串 和 时间可以转换为yyyy-MM-dd HH:mm:ss格式
package com.xiaohan.bootdemo.util;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class JacksonUtils {
/* 默认时间转换格式 */
private static String pattern = "yyyy-MM-dd HH:mm:ss";
/* null不序列化 时间转换 yyyy-MM-dd HH:mm:ss 格式 */
public static ObjectMapper createObjectMapperNullNotEcho() {
ObjectMapper objectMapper = createObjectMapper(false, pattern);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return objectMapper;
}
/* null不序列化 时间转换指定格式 */
public static ObjectMapper createObjectMapperNullNotEcho(String pattern) {
ObjectMapper objectMapper = createObjectMapper(false, pattern);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return objectMapper;
}
/* 可指定是否替换null为空字符串"" 时间转换 yyyy-MM-dd HH:mm:ss 格式*/
public static ObjectMapper createObjectMapper(boolean nullToString) {
return createObjectMapper(nullToString,pattern);
}
/* 可指定是否替换null为空字符串"" 时间转换指定格式 */
public static ObjectMapper createObjectMapper(boolean nullToString, String pattern) {
ObjectMapper objectMapper = nullToString ? new ObjectMappingNullToString() : new ObjectMapper();
if (pattern != null){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
objectMapper.setDateFormat(simpleDateFormat);
}
return objectMapper;
}
public static class ObjectMappingNullToString extends ObjectMapper {
public ObjectMappingNullToString() {
super();
// 空值处理为空串
this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException {
jg.writeString("");
}
});
}
}
}
接下来创建RedisUtils
package com.xiaohan.bootdemo.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtils {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private ValueOperations<String, String> valueOperations;
/* 默认过期时长,单位:秒 */
public final static long DEFAULT_EXPIRE = 60 * 60 * 24;
/* 不设置过期时长 */
public final static long NOT_EXPIRE = -1;
public void set(String key, Object object) throws JsonProcessingException {
set(key, object, DEFAULT_EXPIRE);
}
public void set(String key, Object object, long expire) throws JsonProcessingException {
if (expire == NOT_EXPIRE) {
valueOperations.set(key, toJson(object));
} else {
valueOperations.set(key, toJson(object), expire, TimeUnit.SECONDS);
}
}
/* 获取指定类型的值 刷新生存时长 */
public <T> T get(String key, Class<T> clazz, long expire) throws IOException {
String value = valueOperations.get(key);
if (expire != NOT_EXPIRE) {
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
return value == null ? null : fromJson(value, clazz);
}
/* 获取指定类型的值 不刷新生存时长 */
public <T> T get(String key, Class<T> clazz) throws IOException {
return get(key, clazz, NOT_EXPIRE);
}
/* 获取String类型的值 刷新生存时长 */
public String get(String key, long expire) {
String value = valueOperations.get(key);
if(expire != NOT_EXPIRE){
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
return value;
}
/* 获取String类型的值 不刷新生存时长 */
public String get(String key) {
return get(key,NOT_EXPIRE);
}
/* 删除 */
public void delete(String key) {
redisTemplate.delete(key);
}
/**
* Object转成JSON数据
*/
private String toJson(Object object) throws JsonProcessingException {
if (object instanceof Integer || object instanceof Long || object instanceof Float || object instanceof Double || object instanceof Boolean || object instanceof String) {
return String.valueOf(object);
}
ObjectMapper objectMapper = JacksonUtils.createObjectMapper(true, null);
// ObjectMapper objectMapper = JacksonUtils.createObjectMapperNullNotEcho(null);
return objectMapper.writeValueAsString(object);
}
/**
* JSON数据,转成Object
*/
private <T> T fromJson(String json, Class<T> clazz) throws IOException {
ObjectMapper objectMapper = JacksonUtils.createObjectMapper(true, null);
return objectMapper.readValue(json, clazz);
}
}
然后创建测试类进行测试
package com.xiaohan.bootdemo;
import com.xiaohan.bootdemo.entity.UserEntity;
import com.xiaohan.bootdemo.util.RedisUtils;
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.io.IOException;
import java.util.Date;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTests {
@Autowired
private RedisUtils redisUtils;
@Test
public void testSet() throws IOException {
UserEntity userEntity =new UserEntity();
userEntity.setId(1);
userEntity.setName("张三");
userEntity.setCreateTime(new Date());
redisUtils.set(userEntity.getId()+"",userEntity);
String s = redisUtils.get(userEntity.getId() + "");
System.err.println(s);
UserEntity user = redisUtils.get(userEntity.getId() + "",UserEntity.class);
System.err.println(user);
redisUtils.delete(userEntity.getId()+"");
s = redisUtils.get(userEntity.getId() + "");
System.err.println(s);
}
}
输出结果
{"id":1,"name":"张三","createTime":1502470327435}
UserEntity{id=1, name='张三', createTime=Sat Aug 12 00:52:07 CST 2017}
null
接下来我们来做个切面类
pom.xml加入aop组件
<!-- aop组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
新建一个切面类
package com.xiaohan.bootdemo.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
/**
* Redis切面处理类
*/
@Aspect
@Configuration
public class RedisAspect {
private Logger logger = LoggerFactory.getLogger(getClass());
//是否开启redis缓存 true开启 false关闭
@Value("${spring.redis.open: #{false}}")
private boolean open;
@Around("execution(* com.xiaohan.bootdemo.util.RedisUtils.*(..))")
public Object around(ProceedingJoinPoint point) throws Throwable {
Object result = null;
if(open){
try{
result = point.proceed();
}catch (Exception e){
logger.error("redis error", e);
throw new RuntimeException("Redis服务异常");
}
}
return result;
}
}
将 application.yml中的redis open设为true
image.png
在运行测试类就好了
网友评论