SpringCache(redis)
pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
开启缓存
@EnableCaching
@SpringBootApplication
public class ChemicalApplication {
}
fastjson序列化
FastJson2JsonRedisSerializer.java
package com.meeno.chemical.common.redis;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.NoArgsConstructor;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.stereotype.Component;
import java.nio.charset.Charset;
/**
* @description: fastJsonRedis序列化
* @author: Wzq
* @create: 2020-05-28 19:23
*/
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
public FastJson2JsonRedisSerializer(Class<T> clazz) {
super();
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);
}
}
redisConfig(配置类)
RedisConfig.java
package com.meeno.chemical.common.redis;
import com.alibaba.fastjson.parser.ParserConfig;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
/**
* @description:redis配置类
* @author: Wzq
* @create: 2020-05-28 19:24
*/
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
/**
* redis数据库
*/
public static Integer database;
/**
* host
*/
public static String host;
/**
* 端口
*/
public static Integer port;
/**
* password
*/
public static String password;
/*注入配置*/
@Value("${spring.redis.database}")
public void setDatabase(Integer database){
RedisConfig.database = database;
}
@Value("${spring.redis.host}")
public void setHost(String host){
RedisConfig.host = host;
}
@Value("${spring.redis.port}")
public void setPort(Integer port){
RedisConfig.port = port;
}
@Value("${spring.redis.password}")
public void setPassword(String password){
RedisConfig.password = password;
}
@Autowired
private RedisConnectionFactory factory;
@Bean
public RedisSerializer fastJson2JsonRedisSerializer() {
return new FastJson2JsonRedisSerializer<Object>(Object.class);
}
@Bean
@Primary//当有多个管理器的时候,必须使用该注解在一个管理器上注释:表示该管理器为默认的管理器
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
//初始化一个RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
//序列化方式3 JSONObject
RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(fastJson2JsonRedisSerializer());
RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
//设置过期时间 30天
defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofDays(30));
//初始化RedisCacheManager
RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
//设置白名单---非常重要********
/*
使用fastjson的时候:序列化时将class信息写入,反解析的时候,
fastjson默认情况下会开启autoType的检查,相当于一个白名单检查,
如果序列化信息中的类路径不在autoType中,
反解析就会报com.alibaba.fastjson.JSONException: autoType is not support的异常
可参考 https://blog.csdn.net/u012240455/article/details/80538540
*/
ParserConfig.getGlobalInstance().addAccept("com.");
return cacheManager;
}
//fastjson
@Bean(name="redisTemplate")
public RedisTemplate<String, Object> fastJsonRedisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
//redis开启事务
template.setEnableTransactionSupport(true);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(fastJson2JsonRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(fastJson2JsonRedisSerializer());
template.setDefaultSerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
使用注解缓存
# 查询缓存,不存在新增并返回
@Cacheable(value = "area:tree")
# 删除缓存
@CacheEvict(value = "employeeDeviceUuid",allEntries = true)
SpringCache(redis)的更多相关文章
- SpringBoot2.X + SpringCache + redis解决乱码问题
环境:SpringBoot2.X + SpringCache + Redis Spring boot默认使用的是SimpleCacheConfiguration,使用ConcurrentMapCach ...
- SpringBoot 结合 Spring Cache 操作 Redis 实现数据缓存
系统环境: Redis 版本:5.0.7 SpringBoot 版本:2.2.2.RELEASE 参考地址: Redus 官方网址:https://redis.io/ 博文示例项目 Github 地址 ...
- SpringCache与redis集成,优雅的缓存解决方案
缓存可以说是加速服务响应速度的一种非常有效并且简单的方式.在缓存领域,有很多知名的框架,如EhCache .Guava.HazelCast等.Redis作为key-value型数据库,由于他的这一特性 ...
- SpringCache学习之操作redis
一.redis快速入门 1.redis简介 在java领域,常见的四大缓存分别是ehcache,memcached,redis,guava-cache,其中redis与其他类型缓存相比,有着得天独厚的 ...
- spring-boot的spring-cache中的扩展redis缓存的ttl和key名
原文地址:spring-boot的spring-cache中的扩展redis缓存的ttl和key名 前提 spring-cache大家都用过,其中使用redis-cache大家也用过,至于如何使用怎么 ...
- SpringBoot30 整合Mybatis-Plus、整合Redis、利用Ehcache实现二级缓存、利用SpringCache和Redis作为缓存
1 环境说明 JDK: 1.8 MAVEN: 3. SpringBoot: 2.0.4 2 SpringBoot集成Mybatis-Plus 2.1 创建SpringBoot 利用IDEA创建Spri ...
- SpringCache整合Redis
之前一篇文章 SpringBoot整合Redis 已经介绍了在SpringBoot中使用redisTemplate手动 操作redis数据库的方法了.其实这个时候我们就已经可以拿redis来做项目了, ...
- 缓存策略:redis缓存之springCache
最近通过同学,突然知道服务器的缓存有很多猫腻,这里通过网上查询其他人的资料,进行记录: 缓存策略 比较简单的缓存策略: 1.失效:应用程序先从cache取数据,没有得到,则从数据库中取数据,成功后,放 ...
- Spring+Mybatis基于注解整合Redis
基于这段时间折腾redis遇到了各种问题,想着整理一下.本文主要介绍基于Spring+Mybatis以注解的形式整合Redis.废话少说,进入正题. 首先准备Redis,我下的是Windows版,下载 ...
随机推荐
- 序-WEB方向指南
WEB 这个方向其实是目前从业人员最多的方向,也是学习安全门槛最低的方向,当然也是最容易恰饭的方向. 我从入行到现在也依旧没有脱离它,毕竟在我这个小城市.小圈子里,不干这个好像就要没饭吃了,但是你说它 ...
- Nacos源码分析-事件发布机制
温馨提示: 本文内容基于个人学习Nacos 2.0.1版本代码总结而来,因个人理解差异,不保证完全正确.如有理解错误之处欢迎各位拍砖指正,相互学习:转载请注明出处. Nacos的服务注册.服务变更等功 ...
- python + pytest基本使用方法(运行测试&测试报告)
import pytest# 1.运行名称中包含某字符串的测试用例#名称中含add 的测试用例# 执行: pytest -k add test_assert.py# 2.减少测试的运行冗长# 执行: ...
- 安装Go语言支持及Gogs版本管理工具
安装Go语言支持及Gogs版本管理工具 1. GO 语言: 1.1 介绍 1.1.1 官方介绍: The Go programming language is an open source proje ...
- 解决 centerOS7部署ajango2.2.x版本 报SQLite 3.8.3 or later is required (found 3.7.17).错误
在CentOS7上部署Django的时候,遇到了一些问题,写篇笔记记录解决过程. 报错信息 当python3 manage.py runserver启动django项目的时候,就会出现报错信息如下: ...
- 关于maven打包与jdk版本的一些关系
最近让不同JAVA版本的容器maven打包折腾的不行,终于理出了一点头绪.在这里记录下备忘. 1. Maven与jdk版本的关系 先明确一个概念,关高版本JDK运行maven,是可以打出低版本的JAV ...
- vue知识点---element el-date-picker 插件默认时间属性default-value怎么赋值?
参考网址: http://www.imooc.com/wenda/detail/509359 默认值,你放到 v-model里面就好. v-model="time" data(){ ...
- vue 使用 lang="scss" 报错
npm install sass-loader@7.3.1 --save-dev npm install node-sass --save npm install style-loader --sav ...
- jquery.autocomplete 使用解析
页面引用 <script type="text/javascript" src="${base}/autocom/jquery-1.8.2.min.js" ...
- Django JSONField/HStoreField SQL注入漏洞(CVE-2019-14234)
复现 访问http://192.168.49.2:8000/admin 输入用户名admin ,密码a123123123 然后构造URL进行查询,payload: http://192.168.49. ...