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版,下载 ...
随机推荐
- 单点登录(SSO)实现原理(转)
简介 单点登录是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统的保护资源,若用户在某个应用系统中进行注销登录,所有的应用系统都不能再直接访问保护资源,像一些知名的大型网站,如:淘 ...
- LVGL|lvgl中文手册(lvgl中文文档教程)
lvgl官方的教程是英文的,这个是我在做项目时根据lvgl官方文档做出来的lvgl中文文档(持续更新维护),不仅仅只是生硬照搬lvgl官方文档的翻译,同时总结了我们在实际开发中遇到的各种细节,让这个文 ...
- ARC 122 简要题解
ARC 122 简要题解 传送门 A - Many Formulae 考虑对于每个数分别算其贡献. 通过枚举该数前面的符号,借助一个非常简单的 \(\mathrm{DP}\)(\(f_{i,0/1}\ ...
- 禅道项目管理软件-Linux上一键安装
一.安装 1.将安装包直接解压到/opt目录下 特别说明:不要解压到别的目录再拷贝到/opt/,因为这样会导致文件的所有者和读写权限改变,也不要解压后把整个目录777权限. 可以使用命令: tar - ...
- ORB-SLAM3论文阅读:ORB-SLAM3: An Accurate Open-Source Library for Visual, Visual-Inertial and Multi-Map SLAM
简介 ORB-SLAM3是第一个能在单目.双目.RGBD鱼眼相机和针孔相机模型下运行视觉.视觉-惯导以及多地图SLAM的系统.其贡献主要包括两方面:提出了完全依赖于最大后验估计的紧耦合视觉-惯导SLA ...
- python基础之os模块操作
# os模块 目录相关内置库import os# . 当前目录 .. 返回上一级目录# 1. os.path.abspath() --获取当前文件的绝对路径(不包含os模块.py) pwd# path ...
- 光学动作捕捉系统中的反光标识点(Marker点)
动作捕捉系统本质上是一种定位系统,通常需要在目标物布置定位设备进行追踪.以红外光学为原理的动作捕捉系统,主要由由光学镜头.动作捕捉软件.反光标识点.POE交换机.和若干配件组成,其中反光标识点(Mar ...
- Python基础之subprocess
前言 subprocess这个函数很好用,类似于控制台执行,功能很多,今天先介绍subprocess调用exe,并行调用两个或两个以上的exe. Subprocess调用exe 调用exe有几种方式, ...
- U 跳转中加入变量参数的写法
href="{:U('Message/news?id='.$vo['messageid'].'')}" 就是在U方法里如果参数是变量就用 '.$i.'代替 {$i} <a h ...
- DC-9 靶机渗透测试
DC-9 渗透测试 冲冲冲,好好学习 DC系列的9个靶机做完了,对渗透流程基本掌握,但是实战中出现的情况千千万万,需要用到的知识面太广了,学不可以已. 靶机IP: 172.66.66.139 kali ...