Java项目中玩转Redis6.0客户端缓存

Redis5.0.14 与 6.2.6 差异 Redis 5.0.14 与 6.2.6 的 核心差异 及对 Java 程序的 影响分析,涵盖协议、性能、安全性等关键领域 阅读详情

Redis6.0中的新特性 客户端缓存 client-side caching ,通过telnet连接模拟客户端,测试了三种客户端缓存的工作模式,这篇文章我们就来点硬核实战,看看客户端缓存在java项目中应该如何落地。

铺垫

首先介绍一下今天要使用到的工具 Lettuce ,它是一个可伸缩线程安全的redis客户端。多个线程可以共享同一个 RedisConnection ,利用nio框架 Netty 来高效地管理多个连接。

放眼望向现在常用的redis客户端开发工具包,虽然能用的不少,但是目前率先拥抱redis6.0,支持客户端缓存功能的却不多,而lettuce就是其中的领跑者。

我们先在项目中引入最新版本的依赖,下面正式开始实战环节:

<dependency>
    <groupId>io.lettuce</groupId>
    <artifactId>lettuce-core</artifactId>
    <version>6.1.8.RELEASE</version>
</dependency>

实战

在项目中应用lettuce,开启并使用客户端缓存功能,只需要下面这一段代码:

public static void main(String[] args) throws InterruptedException {
    // 创建 RedisClient 连接信息
    RedisURI redisURI= RedisURI.builder()
            .withHost("127.0.0.1")
            .withPort(6379)
            .build();
    RedisClient client = RedisClient.create(redisURI);
    StatefulRedisConnection<String, String> connect = client.connect();
    
    Map<String, String> map = new HashMap<>();
    CacheFrontend<String,String> frontend=ClientSideCaching.enable(CacheAccessor.forMap(map),
            connect, TrackingArgs.Builder.enabled().noloop());

    String key="user";
    while (true){
        String value = frontend.get(key);
        System.out.println(value);
        TimeUnit.SECONDS.sleep(10);
    }
}

上面的代码主要完成了几项工作:

  • 通过 RedisURI 配置redis连接的标准信息,并建立连接
  • 创建用于充当本地缓存的 Map ,开启客户端缓存功能,建立一个缓存访问器 CacheFrontend
  • 在循环中使用 CacheFrontend ,不断查询同一个key对应的值并打印

启动上面的程序,控制台会不断的打印 user 对应的缓存,在启动一段时间后,我们在其他的客户端修改 user 对应的值,运行的结果如下:

可以看到,在其他客户端修改了key所对应的值后,打印结果也发生了变化。但是到这里,我们也不知道 lettuce 是不是真的使用了客户端缓存,虽然结果正确,但是说不定是它每次都重新执行了 get 命令呢?

所以我们下面来看看源码,分析一下具体的代码执行流程。

分析

在上面的代码中,最关键的类就是 CacheFrontend 了,我们再来仔细看一下上面具体实例化时的语句:

CacheFrontend<String,String> frontend=ClientSideCaching.enable(
        CacheAccessor.forMap(map),
        connect,
        TrackingArgs.Builder.enabled().noloop()
);

首先调用了 ClientSideCaching 的&n

如何在 Java 中使用 Redis 实现缓存优化? 在今天的开发环境中,我们往往面临着系统响应慢、数据库压力过大等问题,尤其是在高并发、高流量的应用场景中。为了提高系统的性能,减少数据库查询次数,优化响应时间,缓存技术就显得尤为重要。你也许已经听说过 Redis,它不仅是一款功能强大的内存数据存储工具,还是提升系统性能的“秘密武器”。今天,我们就来详细探讨如何在 Java 项目中使用 Redis 来进行缓存优化。通过实际的代码示例和案例分析,我们将一步步解锁 Redis 在 Java 中的应用,帮助你提升系统性能,降低数据库的负担。 阅读详情

相关推荐

HDMI协议介绍(一)--Overview

HDMI全称(High Definition Multimedia Interface)高清多媒体接口,支持在单线缆上传输全数字高清视频和多声道音频。

SlamDunk的博客 2万+

基于R语言 meta/metafor 包进行荟萃分析(一)

在此部分中,使用连续结果详细描述了通用逆方差方法及其在meta分析中的应用,还介绍了固定效应法和随机效应法。我们已经展示了如何分别将典型数据与metacont和metagen函数一起使用,以及如何print和绘制森林图。我们还讨论了估计研究间方差的各种方法,并将Hartung-Knapp平差描述为经典随机效应方法的替代方法。此外,我们还说明了byvar选项的使用,这使得亚组分析更加简单。关于亚组分析的更多细节见后续章节。

Dunaichuanyi的博客 1万+

数据库decimal类型详解:精度、标度与金额计算避坑指南

在关系型数据库中,浮点数精度丢失是常见问题,尤其涉及金额计算时,一分钱误差都可能导致对账失败。decimal类型通过十进制存储方式,将小数当作定点数处理,避免了二进制转换误差,确保运算结果精确。其核心在于精度和标度的合理定义,以及运算舍入规则的控制。在电商订单、汇率转换、税务计算等场景中,decimal是保障数据准确性的关键技术。理解其存储原理和实操细节,能有效规避隐式转换、聚合函数精度等常见坑点,提升系统可靠性。

weixin_32050773的博客 285

十七、SAP-采购订单(STO)

业务逻辑、功能讲解、图文解析、章节总结

m0_72403327的博客 2074

Arduino ESP32 Web服务器从microSD卡读取

Arduino ESP32 Web服务器从microSD卡读取 将网页内容放到SD卡中,当有客户端数据请求时,从SD卡读取信息进行发送,比起SPIFFS文件系统,更节约板上的硬件资源。 SD卡接线说明 ESP32----- SD D5(GPIO 5)-----CS D18(GPIO 18)-----SCK D19(GPIO 19)-----MISO D23()GPIO 23-----MOSI 文件放置 需要把文件放置到SD卡的根目录下。注意SD卡的格式FAT32格式。 实例代码 /*

perseverance51博客 1442

面向干净核心的并行扩展:SAP BTP 上的 side-by-side extensions 全面解读

摘要: SAP的side-by-side extensions是一种与核心系统解耦的云原生扩展模式,通过API和事件驱动实现与SAP S/4HANA等核心系统的松耦合集成。该模式支持独立升级、弹性扩展和高效创新,是SAP官方推荐的clean core关键实现路径。其典型架构包括接口层(OData/REST API、事件通道)、运行层(Cloud Foundry/Kyma/CAP框架)和体验层(Fiori/UI5)。适用场景包括需快速迭代、复用云服务或服务外部用户的业务扩展。实施时需关注安全治理(如XSUAA

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 308

BPC坏点矫正

whatis the Bad Pixel? 坏点为死点,也就是基本不随照度变化呈现光电线性转换的关系。表现为暗态常亮,亮态常暗。 坏点分类:静态坏点:亮坏点,暗坏点。 动态坏点:在一定像素范围内,该点表现正常,而超过这一范围,该点表现的比周围像素要亮。与sensor ...

camerall 1万+

多尺度仿真软件:Copasi_(1).Copasi概述

Copasi(Complex Pathway Simulator)是一款开源的多尺度仿真软件,专为生物化学、系统生物学和合成生物学领域的研究人员设计。它不仅能够模拟细胞内和细胞间的生化反应网络,还能处理代谢途径、信号传导途径和基因调控网络等多种复杂系统。Copasi提供了用户友好的图形界面和强大的命令行接口,支持多种仿真算法和分析工具,使用户能够高效地进行模型构建、仿真和分析。Copasi允许用户创建自定义报告,以便生成特定格式的仿真结果。用户可以通过图形界面或命令行创建自定义报告。

kkchenjj的博客 865

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

深度学习工具包 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")

上一篇: Java内存马攻防实战——攻击基础篇
下一篇: Java反射性能问题,慢在哪里?
JavaMonsterr
博客等级 码龄5年 211粉丝 481原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址