springboot整合redis 重写 redisCacheManager和 reidsTemplate 自定义序列化方式

@Cacheable CacheManager 重写clear方法 根据前缀批量删除redisKey 一、参考文档: https://blog.youkuaiyun.com/qq_36194413/article/details/105833158 https://blog.youkuaiyun.com/llllllllll4er5ty/article/details/106337559 https://www.freesion.com/article/5258202702/ 二、批量删除缓存代码 4.1 自定义RedisCache:(重写方法) @Slf4j public class CustomizedRedisCache e 阅读详情

默认的序列化方式是jdk序列化,我们需要转化为json序列化方式

在springboot1.x版本中,重写缓存管理器

 //缓存管理器
    @Bean
    public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        //设置缓存过期时间
        cacheManager.setDefaultExpiration(10000);
        return cacheManager;
    }    //缓存管理器
   

然而在2.0版本中,这个代码直接报错,原因是RedisCacheManager取消了1.0版本中的public RedisCacheManager(RedisOperations redisOperations)的这个构造方法,所以我们无法再用RedisTemplate作为参数来自定义CacheManager。

2.x中应该这样自定义缓存管理器

@Configuration
public class MyRedisConfig {
    @Bean
    public RedisTemplate<Object, Object> empRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        template.setDefaultSerializer(serializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofDays(1))
                .disableCachingNullValues()
                .serializeKeysWith(RedisSerializationContext.SerializationPair
                .fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();
    }
}
Spring Boot基础学习笔记19:自定义RedisTemplate与RedisCacheManager 文章目录零、学习目标一、为什么要采用自定义Redis缓存序列化机制二、自定义RedisTemplate(一)Redis API 默认序列化机制(二)自定义RedisTemplate序列化机制(三)创建Spring Boot项目 - RedisTemplateDemo(四)创建评论实体类 - Comment(五)创建评论仓库接口 - CommentRepository(六)创建评论服务类 - CommentService(七)创建评论控制器 - CommentController(八)配置应用属性文件 - a 阅读详情

相关推荐

AlphaFold2算法详解

正文:https://www.nature.com/articles/s41586-021-03819-2 补充文件:https://static-content.springer.com/esm/art%3A10.1038%2Fs41586-021-03819-2/MediaObjects/41586_2021_3819_MOESM1_ESM.pdfhttps://static-content.springer.com/esm/art%3A10.1038%2Fs41586-021-03819-2/Med

Daisy4的博客 1万+

spring boot2.0之自定义 RedisCacheManager 的方法

今天在学习spring boot框架的路上遇到了Redis和缓存机制的整合,在试图创建一个 RedisCacheManager 缓存管理器时,遇到了很多问题,接下来和大家分享一下我解决问题的心(xin)路(suan)历程。 一、springboot1.0和2.0的默认创建的 RedisCacheManager 方法是不同的 springboot1.0:RedisCacheManager ...

ping_and_yin的博客 6028

Spring Boot Swagger未授权访问漏洞:原理、风险与修复方案详解

在微服务架构中,API文档管理是开发与运维的重要环节。Swagger作为RESTful API文档生成与调试的标准化工具,通过OpenAPI规范自动生成交互式接口文档,极大提升了开发效率。然而,其默认配置往往缺乏访问控制,导致文档端点直接暴露,形成未授权访问漏洞。从技术原理看,该漏洞源于Spring Boot等框架集成Swagger时,相关端点未纳入安全框架的拦截范围,攻击者可通过扫描常见路径获取完整的接口定义与数据结构。这不仅会造成敏感信息泄露,更可能成为越权操作、数据篡改等深度攻击的入口点。在工程实践中

weixin_42524171的博客 496

java自定义全局缓存_SpringBoot2.3.0自定义RedisCacheManager并对缓存Jackson序列化

版本:spring-boot:2.3.0redis:latest(Docker)依赖org.springframework.bootspring-boot-starter-data-jdbcorg.springframework.bootspring-boot-starter-data-jpaorg.springframework.bootspring-boot-starter-data-redi...

weixin_34771903的博客 662

从建模到调参:基于Simulink的两轮差速机器人轨迹跟踪PID控制全流程解析

本文详细解析了基于Simulink的两轮差速机器人轨迹跟踪PID控制全流程,涵盖运动学建模、仿真环境搭建、PID控制器设计与实现等关键环节。通过Simulink仿真和可视化调试技巧,帮助开发者掌握移动机器人运动控制的核心技术,提升轨迹跟踪精度与性能优化能力。

weixin_28717683的博客 243

Windows Server 2022域控环境下的MDT部署工具安装与配置避坑指南

本文详细介绍了在Windows Server 2022域控环境中安装和配置MDT(Microsoft Deployment Toolkit)的全流程,包括ADK与Windows PE的精准安装、MDT高级配置、部署工作流构建及性能优化技巧。通过实战指南帮助IT管理员实现自动化系统部署,提升企业IT运维效率,特别适用于需要静默下发系统的大规模部署场景。

weixin_28481133的博客 435

Springboot+Redis 重写Redistemplate实现序列化

通过 RedisSerializer接口的实现方法中我们可以看出,有如下几种序列化方法,我们接下来主要使用的是Jackson2JsonRedisSerializer和StringRedisSerializer(分别用来序列化value和key)至于为什么是四种,源码中只有四种,所以设置四种就好了(源码部分在代码中注释起来了)这个类里面只有一个RedisTemplate一个方法,首先我们需要将序列化配置好。首先,因为系统自带的序列化方式并不复合我们自己的需求,而源码中。并不复合我们的实际需求。

qq_52810376的博客 1251

20220601超简单百度地图街景图片爬取+绿视率计算

真的不难咯。

weixin_39676904的博客 1万+

SpringBoot项目中整合Redis非关系数据库作为内存缓存框架,测试数据读取,new RedisCacheManager(redisTemplate)没有此构造。

显示没有此构造: 解决方法: 分析参考:https://blog.youkuaiyun.com/sy793314598/article/details/80719224

qq_35872777的博客 6941

Zabbix Trigger actions访问出现500

本篇博客详细介绍了Zabbix访问'Trigger actions'出现的错误状况,访问界面出现500,并提供了解决方案。

格子的博客 562

js逆向第3例:蝉妈妈大屏实时数据formDataSign加密

蝉妈妈大屏抖音直播实时数据是抓取抖音直播间数据的实时数据,有类似需求的公司但没有能力去搞定抖音,抓取蝉妈妈数据也是一个不错的选择。接下来就是调试找到加密点,说句题外话蝉妈妈的所有js文件打包方式用的都是webpack5,那如何区分打包方式可以阅读这篇文章。时间戳 ,经过观察发现加密参数是实时变化的。这个函数扣下来,在浏览器控制台中测试一下。言归正传,打断点找到变量。继续打断点向上找又发现了。查看请求参数,可以看到。请求的内容,那么这个。

花臂不花Home 1539

RedisCacheManager 2.x 源码解析

2.X RedisCacheManager中没有RedisTemplate了,看起来更加复杂了,我们先弄清楚各个成员变量的含义,这样后面看源码的过程就会明了一些。 1. RedisCacheManager 里面的各个对象在2-5中详细解释。 public class RedisCacheManager extends AbstractTransactionSupportingCacheManager { // cacheWriter,实际对Redis进行读写,键值都是byte[]。 private fi

haiku的博客 650

【Clickhouse】Cannot allocate block number in Zookeeper write prefix view location

我有一个问题,我CK集群跑批的时候,replicated表变成只读的了下面是CK的报错和当时ZK的日志。下面是zk报错开始 我认为是写入的时候,压力太大,ZK扛不住了,就按照博客里的建议优化了ZK的参数,现在偶尔还会只读,zk报错都是图里的那种clickhouse的集群是5分片的集群,数据量比较大。每小时批量一次,每次2-10W条数据,字段的话,不到200个字段,使用的 jdbc sink写入。

九师兄 836

关于SpringBoot中使用RedisCacheManager没有构造函数的问题

  在SpringBoot2.0中, 使用 public CacheManager cacheManager(RedisTemplate redisTemplate) { //问题在这里 RedisCacheManager rcm = new RedisCacheManager(redisTemplate); rcm.setDefaultExpiration(60);//秒 retu...

A追风筝的人A 3775

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

springboot 整合redis作为缓存,自定义json序列化对象,解决无构造函数报错。

原理:CacheManager===Cache缓存组件来实际给缓存中存取数据 1)、引入redis的starter,容器中保存的是 RedisCacheManager 2)、RedisCacheManager 帮我们创建 RedisCache来作为缓存组件;RedisCache通过操作redis缓存数据 3.默认保存数据都是object,利用自带的序列化保存,我们需要将序列化保存为json 当我们引入redis的starter ,cacheManager变为RediscacheManager 创建.

weixin_53472653的博客 1832

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

RedisTemplate的配置

【代码】RedisTemplate的配置。

廖奕泽的博客 1079

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

自定义RedisTemplate和RedisCacheManager

默认的RedisTemplate和RedisCacheManager的使用JDK的序列化方式,可以自定义为string和json序列化 @Configuration public class MyRedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws Unknow

weixin_43631820的博客 2265

springboot2.0重写RedisCacheMange自定义设置过期时间

@Override @Cacheable(cacheNames = "cache#45", key = "#key") public String test(String key) { System.out.println(key); return "12345"; } 通过cacheNames所传递的值进行处理来设置过期时间,如:cache#45 cache代表原来的前缀,...

New_CJ的博客 2139

Redis(二)redisTemplate

持久化 redis是内存数据库,服务器重启,数据会丢失 持久化机制: RDB:默认方式,不需要进行配置 在一定的间隔事件中,检测key的变化情况,然后持久化数据 AOF:日志记录的方式,记录每一条命令的操作,可以每次命令操作后,持久化数据 RDB 在redis.windows.conf文件中修改配置 # 在15分钟有至少1个key改变持久化一次 save 900 1 # 在5分钟有至少10个k...

Aizen_Sousuke的博客 548

springboot 配置redisTemplate 以及缓存管理器CacheManager

贴核心吧,直接看代码吧,注释不少 import java.time.Duration; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.context.ann...

qq_42962779的博客 2392

SpringBoot配置RedisTemplate和RedisCacheManager

import com.dxy.cache.pojo.Dept; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; i...

眼前一座山,踏平它 1万+

RedisCacheManager

在springbooot2.0以上RedisCacheManager发生了变化… @SuppressWarnings("rawtypes") public RedisCacheManager(RedisOperations redisOperations) { this(redisOperations, Collections.<String> emptyList()); } 去除了上面的构造方法 所以在配置时报错 RedisCacheManager rcm = new R

iijik55的博客 2812

Redis缓存的使用和基于SpringBoot1.x和SpringBoot2.x的RedisCacheManager配置使用详解

* Redis是一个开源的,内存中的数据机构存储系统,它可以作为数据库,缓存和消息中间件。 * 使用:安装redis,引入redis的starter,配置redis * 原理:CacheManager == Cache 缓存组件来实际给缓存中存取数据,替换默认的SimpleCacheConfiguration * 1.引入redis的starter,容器中保存的是RedisCacheManager * 2.RedisCacheManage...

xy294636185的博客 3516

SpringBoot缓存详解

本文主要介绍SpringBoot缓存的基本使用。

m0_50202747的博客 4213

扩展spring cache 支持缓存多租户及其自动过期

为什么80%的码农都做不了架构师?>>> ...

weixin_33813128的博客 543

springboot2 配置redis,RedisTemplate,RedisCache

springboot1.5的版本redis客户端默认是jedis,2.0以上版本默认是lettuce 本文采用lettuce,就是把application.yml配置文件里的jedis换成lettuce, 一、pom.xml &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache...

6895
上一篇: spring boot框架与Redis整合Unexpected character (‘¬‘ (code 172)): expected a valid value
下一篇: 二叉搜索树与双向链表(三十七)
software_Manito
博客等级 码龄8年 6粉丝 90原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值