Spring Boot Redis 集成,springredis
Spring Boot 简单配置 Redis
简单介绍Spring Boot 中 Redis的使用
- Maven 构建
- Redis 缓存
1. 添加redis支持
在pom.xml中
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
2. redis 配置
@Configuration
@EnableCaching
public class RedisConfigure extends CachingConfigurerSupport {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new RedisObjectSerializer());
return template;
}
@Bean
public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
// 设置缓存过期时间
// rcm.setDefaultExpiration(60);// 秒
return rcm;
}
//自定义key生成策略
@Bean
public KeyGenerator wiselyKeyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
}
RedisObjectSerializer.java
Redis序列化java 类
public class RedisObjectSerializer implements RedisSerializer<Object> {
private Converter<Object, byte[]> serializer = new SerializingConverter();
private Converter<byte[], Object> deserializer = new DeserializingConverter();
static final byte[] EMPTY_ARRAY = new byte[0];
public Object deserialize(byte[] bytes) {
if (isEmpty(bytes)) {
return null;
}
try {
return deserializer.convert(bytes);
} catch (Exception ex) {
throw new SerializationException("Cannot deserialize", ex);
}
}
public byte[] serialize(Object object) {
if (object == null) {
return EMPTY_ARRAY;
}
try {
return serializer.convert(object);
} catch (Exception ex) {
return EMPTY_ARRAY;
}
}
private boolean isEmpty(byte[] data) {
return (data == null || data.length == 0);
}
}
3.redis服务器配置
# REDIS (RedisProperties)
spring.redis.database= # database name
spring.redis.host=localhost # server host
spring.redis.password= # server password
spring.redis.port=6379 # connection port
spring.redis.pool.max-idle=8 # pool settings ...
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.sentinel.master= # name of Redis server
spring.redis.sentinel.nodes= # comma-separated list of host:port pairs
4. 应用
测试实体类
java代码:
public class Http implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(name = "http_id")
private String httpId;//
@Column(name = "http_name")
private String httpName;//
@Column(name = "http_url")
private String httpUrl;// 检测url
@Column(name = "http_status")
private int httpStatus;// 当前状态(0 未检测,1正常 2 异常)
@Column(name = "http_msg")
private String httpMsg;// 检测url 返回的信息
@Column(name = "http_method")
private int httpMethod;// (0:get ,1:post)
@Column(name = "http_error_num")
private int httpErrorNum;//
@Temporal(TemporalType.TIMESTAMP)
@org.hibernate.annotations.CreationTimestamp
@Column(name = "http_last_check_time", columnDefinition = "DATE DEFAULT CURRENT_DATE ", updatable = false)
private Date httpLastCheckTime;// 最后一次检查时间
@Temporal(TemporalType.TIMESTAMP)
@org.hibernate.annotations.CreationTimestamp
@Column(name = "http_create_time", columnDefinition = "DATE DEFAULT CURRENT_DATE", updatable = false)
private Date httpCreateTime;//
@Temporal(TemporalType.TIMESTAMP)
@org.hibernate.annotations.CreationTimestamp
@Column(name = "http_modify_time", columnDefinition = "DATE DEFAULT CURRENT_DATE ON UPDATE CURRENT_TIMESTAMP", updatable = true)
private Date httpModifyTime;//
//忽略 get set
使用演示:
@Service
public class DemoService {
@Inject
private HttpJpa httpJpa;
@Cacheable(value = "httpcache", keyGenerator = "wiselyKeyGenerator")
public Http findHttp(String id) throws MyException {
System.out.println("-----0.没有缓存 调用这里------");
Http http = httpJpa.findOne(id);
if (http == null) {
throw new MyException("0001", "http id 不存在");
}
return http;
}
}
Controller :
get 方法里面执行了两次findHttp() 方法,如果出现两次”—–0.没有缓存 调用这里——”打印就证明没使用到缓存,如果只打印了一次即证明成功了。
@RestController
@RequestMapping("/")
public class RedisController {
@Inject
DemoService demoService;
@RequestMapping("get")
public Object get(String id) throws MyException {
demoService.findHttp(id);
return demoService.findHttp(id);
}
}
只出现了一次打印
Redis 的数据
Spring Boot 集成Redis 成功啦~~
下次分享Redis 更深入的使用~期待下次见面
本站文章为和通数据库网友分享或者投稿,欢迎任何形式的转载,但请务必注明出处.
同时文章内容如有侵犯了您的权益,请联系QQ:970679559,我们会在尽快处理。