济世魔王
springboot 2 集成 redis 缓存
springboot 缓存
为了实现是在数据中查询数据还是在缓存中查询数据,在application.yml 中将mybatis 对应的mapper 包日志设置为debug 。
spring:
datasource:
username: root
password: rootpassword
url: jdbc:mysql://localhost:3306/springboot
driver-class-name: com.mysql.jdbc.Driver
debug: true
logging:
level:
com:
springbootmybatis:
mapper: debug
然后在springboot的主类上添加 @EnableCaching 启动缓存。
然后在service 类中的方法上添加上缓存注解。
@Cacheable(value = "user")
public User selectUserById(Integer id) {
User user = userMapper.selectUserById(id);
return user;
}
@Cacheable
默认的是将传入参数(id)作为缓存的 key ,方法的返回值作为 value 存入缓存中 。
在方法 selectUserById(Integer id ) 执行之前 先去根据 key 去缓存中查询是否有该 key 的数据,如果有,则直接在缓存中查询数据,然后返回,不再执行 selectUserById 方法,如果没有在缓存中查到该 key 的数据,才回去执行 selectUserById 方法。
@CachePut
@CachePut(value = "user")
public User updateUser(User user) {
userMapper.updateUser(user);
return user;
}
默认的是将传入参数(id)作为缓存的 key ,@CachePut 在方法执行之后执行,将方法返回的结果写入缓存,
从缓存中查询到的仍然是旧的缓存数据,需要在 @CachePut(value = "user",key = "#result.id") 或者@CachePut(value = "user",key = "#user.id") 只要在 key 设置为 user 的 id ,然后根据id 去查询,就能从缓存中获取修改后的数据。
@CacheEvict
@CacheEvict(value = "user",key = "#id")
清除操作默认是在对应方法成功执行之后触发的,即方法如果因为抛出异常而未能成功返回时也不会触发清除操作 ,可以使用 beforeInvocation 改变删除缓存的时间,当将 beforeInvocation 设置为 true 时,会在执行方法之前删除缓存中指定的元素,不管方法执行是否存在异常,都会删除缓存。 删除指定 key 的缓存。allEntries 默认为 false ,当为 true 时,会忽略指定的 key ,删除所有缓存元素。不指定 key 时默认一方法的参数作为缓存的 key。
@Caching
@Caching注解可以让我们在一个方法或者类上同时指定多个Spring Cache相关的注解。其拥有三个属性:cacheable、put和evict,分别用于指定@Cacheable、@CachePut和@CacheEvict。
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Caching {
Cacheable[] cacheable() default {};
CachePut[] put() default {};
CacheEvict[] evict() default {};
}
@Caching(cacheable = @Cacheable("users"), evict = { @CacheEvict("cache2"),
@CacheEvict(value = "cache3", allEntries = true) })
public List<User> selectUser() {
List<User> users = userMapper.selectUser();
return users;
}
使用redis 缓存:
导入对应的jar:使用fastjson 来序列化value
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
在application.yml 添加配置:
spring:
redis:
host: #redis 安装的IP,其他的可以不用配置,默认的就可以满足测试需要
在springboot 1 中配置redis
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
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;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@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();
}
};
}
@Bean
public CacheManager cacheManager(
@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
return new RedisCacheManager(redisTemplate);
}
@Bean
public RedisTemplate<String, String> redisTemplate(
RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);
template.setValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
private static class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
public FastJsonRedisSerializer(Class<T> clazz) {
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return (T) JSON.parseObject(str, clazz);
}
}
}
然后在测试类上加上缓存的注解就可以在redis中查看已经序列化成json格式的数据。
在springboot2 中配置redis
其他的配置不用动,需要修改RedisConfig.java 因为springboot2 中new RedisCacheManager(redisTemplate);被遗弃了
@Bean
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
//初始化一个RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
//设置CacheManager的值序列化方式为 fastJsonRedisSerializer,但其实RedisCacheConfiguration默认使用StringRedisSerializer序列化key,
ClassLoader loader = this.getClass().getClassLoader();
FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer<>(loader.getClass());
RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer);
RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
return cacheManager;
}
这样设置就可以正常使用了
posted on 2018-07-03 11:17 济世魔王 阅读(25) 评论(0) 编辑 收藏
刷新评论刷新页面返回顶部 注册用户登录后才能发表评论,请 登录 或 注册,访问网站首页。 【推荐】超50万VC++源码: 大型组态工控、电力仿真CAD与GIS源码库!【福利】校园拼团福利,腾讯云1核2G云服务器10元/月!
【大赛】2018首届“顶天立地”AI开发者大赛

· 恒生指数宣布纳入小米集团:成港股优质资产风向标
· 世界杯直播背后的黑科技,腾讯云极速高清技术驱动体育直播发展
· 22岁印度大学生获谷歌天价offer,击败6000人年薪百万
· 小米上市首日收盘价16.8港元 较发行价下跌1.18%
· 微软宣布Windows 8.1平台的翻译应用停止服务
» 更多新闻...

· 断点单步跟踪是一种低效的调试方法
· 测试 | 让每一粒尘埃有的放矢
· 从Excel到微服务
· 如何提升你的能力?给年轻程序员的几条建议
· 程序员的那些反模式
» 更多知识库文章...
导航
公告
昵称:济世魔王园龄:11个月
粉丝:1
关注:3 +加关注
|
||||||
日 | 一 | 二 | 三 | 四 | 五 | 六 |
---|---|---|---|---|---|---|
24 | 25 | 26 | 27 | 28 | 29 | 30 |
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 | 1 | 2 | 3 | 4 |
统计
- 随笔 - 19
- 文章 - 0
- 评论 - 4
- 引用 - 0
搜索
常用链接
随笔分类
随笔档案
最新评论
- 1. Re:在idea 上springboot 1.5.6集成jsp页面
- @nakeyspringboot2.0还没用过,QQ:308539393...
- --济世魔王
- 2. Re:在idea 上springboot 1.5.6集成jsp页面
- @济世魔王能否留个联系方式,方便沟通,我这边springboot是:2.0.0 idea是2016.1.2...
- --nakey
- 3. Re:在idea 上springboot 1.5.6集成jsp页面
- @nakey这是我是用springboot1.5.6 ,idea是2017.2.7,你能说一下你的版本号吗,晚上我回去试一下...
- --济世魔王
- 4. Re:在idea 上springboot 1.5.6集成jsp页面
- 按照你的样子配了,最后访问的时候是404啊,怎么回事?
- --nakey
阅读排行榜
- 1. 在idea 上springboot 1.5.6集成jsp页面(5223)
- 2. springcloud 使用RabbitMq(1414)
- 3. sprignboot 中thymeleaf和freemarker 都存在时,默认选择哪个(971)
- 4. 分布式配置中心(Spring Cloud Config)(64)
- 5. springboot-actuator监控的401无权限访问(48)
评论排行榜
推荐排行榜
Powered by:博客园
Copyright © 济世魔王