Spring Boot中使用缓存Redis、EhCache

009. Spring Boot(1.5.10版本)缓存技术(整合Ehcache+整合@Cacheable整合@CacheEvict+Redis(3.0.0)) Spring Boot 整合 Ehcache EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。 ehcache提供了多种缓存策略,主要分为内存和磁盘两级,所以无需担心容量问题。 spring-boot是一个快速的集成框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从... 阅读详情

缓存相信各位同学都或多或少用到过,毕竟不能把所有压力都给数据库。今天来简单总结一下下在Spring Boot中使用Redis和EhCache缓存O(∩_∩)O~
Spring Boot本身是支持多种缓存实现的,其中提供了4个注解来帮助大家使用缓存:

  • @EnableCaching 开启缓存支持
  • @Cacheable 先检查缓存是否存在,若存在,则直接返回缓存中结果;若不存在,则执行方法获取结果,并将结果放到缓存中
  • @CacheEvict 清除缓存
  • @CachePut 始终执行方法,并将结果放到缓存中

先说一下EhCache,EhCache是在内存中的缓存,也就是说,程序在,缓存就在,程序停了,缓存就没了,要使用EhCache,首先引入pom starter:

	<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
	</dependency>

在启动类上开启缓存支持:

@SpringBootApplication
@EnableCaching
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

下来只需要在方法上加上注解就行了:

@Cacheable(value="user",key = "#user.id")
public User findOne(User user) {
      User u=userRepository.findOne(user.getId());
      return u;
}

可以看到,在注解中指定了value和key两个参数,value是用来归类用的,以上方法所生成的所有缓存在缓存库中都存放在user文件夹下;key是用来指定缓存键值的,它有两种生成策略——默认策略和自定义策略,其默认策略如下:

  • 如果方法没有参数,则使用0作为key
  • 如果只有一个参数,则使用该参数作为key
  • 如果参数多于一个,则使用所有参数的hashCode作为key

很明显,我这里自定义了key,指定为参数user对象的id。
key支持通过Sping EL表达式来指定,几个一看就懂的栗子:

   @Cacheable(value="user", key="#id")
   public User find(Integer id) {
      return null;
   }
   
   @Cacheable(value="user", key="#p0")
   public User find(Integer id) {
      return null;
   }

   @Cacheable(value="user", key="#user.id")
   public User find(User user) {
      return null;
   }

   @Cacheable(value="user", key="#p0.id")
   public User find(User user) {
      return null;
   }

除了上述使用方法参数生成key以外,Spring还提供了一个root对象来生成key:

属性名称描述示例
methodName当前方法名#root.methodName
method当前方法#root.method.name
target当前被调用的对象#root.target
targetClass当前被调用的对象的class#root.targetClass
args当前方法参数组成的数组#root.args[0]
caches当前被调用的方法使用的Cache#root.caches[0].name

另外,如果EhCache有别的设置,那么可以新建一个ehcache.xml,在application.properties中配好这个配置文件即可:

spring.cache.type=ehcache
spring.cache.ehcache.config=static/ehcache.xml

下面说一下Redis,同样首先引入pom starter:

<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

同样通过@EnableCaching打开缓存支持。

由于Redis是独立安装的,它就像数据库一样可以持久化数据,所以必然也像数据库一样有连接地址,在application.yml中配置如下:

	spring:
	  redis:
	    database: 0
	    host: 10.155.20.162
	    port: 6379
	    pool:
	      max-active: 80
	      max-wait: -1
	      max-idle: 80
	      min-idle: 0
	    timeout: 5000

呐,EhCache的时候用的properties配置文件,Redis用的yml配置文件哟,各取所爱吧~

同样在方法上面使用@Cacheable、@CacheEvict、@CachePut来操作缓存。
这里介绍一下keyGenerator,前面key的生成策略就是它控制的,Spring允许我们自定义这个Generator,举个栗子:

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
    //自定义key生成方式
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                String[] value = new String[1];
                Cacheable cacheable = method.getAnnotation(Cacheable.class);
                if (cacheable != null) {
                    value = cacheable.value();
                }
                CachePut cachePut = method.getAnnotation(CachePut.class);
                if (cachePut != null) {
                    value = cachePut.value();
                }
                CacheEvict cacheEvict = method.getAnnotation(CacheEvict.class);
                if (cacheEvict != null) {
                    value = cacheEvict.value();
                }
                sb.append(value[0]);
                sb.append(":");
                sb.append(params[0].toString());
                return sb.toString();
            }
        };
    }

    //缓存管理器
    @Bean
    public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        cacheManager.setDefaultExpiration(43200);  //设置缓存过期时间
        return cacheManager;
    }
    
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory){
        StringRedisTemplate template = new StringRedisTemplate(factory);
        @SuppressWarnings({ "rawtypes", "unchecked" })
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

可以看到,这个Config中有3个Bean,第1个Bean中用注解的value属性+":"+第一个参数作为key值的生成策略;第2个Bean中指定了缓存的全局过期时间;第3个Bean中定义了RedisTemplate。

ok,以上讲了通过注解来操作缓存,不过有的时候,并不一定存在方法,只是单纯地想操作某个key值的缓存,咋办?这个时候就要用到RedisTemplate啦,Spring中自带这个对象,包括上面也自定义了这个对象,我们在需要使用的地方把它注入进来就可以了。不过,通常我们会先写个工具类:

@Service
public class RedisService {
    @Autowired
    @Qualifier("stringRedisTemplate")
    RedisTemplate template;

    public void setValue(String key, Object val) {
        template.opsForValue().set(key, val);
    }

    public void setValue(String key, Object val, int time, TimeUnit unit) {
        template.opsForValue().set(key, val, time, unit);
    }

    public Object getValue(String key) {
        return template.opsForValue().get(key);
    }

    public void deleteValue(String key){
        template.delete(key);
    }
}

可以看到,我这边使用的是stringRedisTemplate,具体还有什么其它类型,各位同学自己去发现一以下吧~

springboot整合ehcache+redis实现双缓存 在一些对并发业务要求较高的场景下,对页面数据的响应是个急需解决的问题,对后端来说,ehcache+redis实现双缓存是解决这一问题的不错思路,而且在不少的电商项目中得到了很好的验证,但我在网上搜寻资料的时候总觉得一些材料不能很好的说明这个问题,要么太复杂,要么太简单,最近抽空思考了一下这一思路的简单实现,下面就用springboot整合ehcache和redis来说明一下实现的过程, 需求说明,... 阅读详情

相关推荐

FPGA实战:MIG IP核AXI接口DDR3读写优化指南

本文详细解析了FPGA中MIG IP核AXI接口的DDR3读写优化策略,涵盖关键参数配置、突发传输技巧及时序收敛方案。通过AXI接口优化和突发长度选择,可实现高达12.8GB/s的理论带宽,提升DDR3访问效率。文章还提供了Vivado配置实例和调试技巧,助力开发者解决FPGA内存控制中的实际问题。

weixin_29168393的博客 545

Springboot2.0整合Redis缓存+Ehcache缓存

整合Redis缓存与Ehcache缓存

Jack方 3646

用野火FPGA开发板(EP4CE10)手把手教你实现一个高精度频率计(附完整Verilog代码)

本文详细介绍了基于野火FPGA开发板(EP4CE10)实现高精度频率计的全过程,涵盖等精度测量法的核心原理、Verilog代码实现及优化技巧。通过实际案例演示,帮助开发者掌握1Hz-50MHz范围、精度达0.1%的频率计设计方法,并提供完整的工程代码和实测数据。

weixin_29261711的博客 439

springboot:缓存不止redis,学会使用本地缓存ehcache

ehcache是基于java开发的本地缓存组件,无需单独安装部署,只要引入jar包就可利用它来实现缓存。所谓本地缓存,就是指存储在JVM堆内存中的临时缓存数据,当然ehcache本身也支持Off-Heap Store机制来使用堆外内存,本地缓存相较于redis性能和响应速度更高。Ehcache的本地缓存还支持过期时间、最大容量、持久化等特性,使得它可以适用于各种不同的缓存场景。

55555的博客 8402

从Microchip SDK到STM32实战:手把手教你移植LAN9252 EtherCAT从站驱动(含EEPROM配置避坑)

本文详细介绍了如何将Microchip SDK中的LAN9252 EtherCAT从站驱动移植到STM32F407平台,包括FSMC接口配置、中断处理适配和EEPROM配置等关键步骤。通过实战指南和避坑技巧,帮助开发者快速实现高性能EtherCAT从站设备的开发,适用于工业自动化领域。

weixin_29197835的博客 446

从Mule ESB到Apache Camel:手把手教你设计一个轻量级企业集成框架的‘心脏’

本文深入探讨了从Mule ESB到Apache Camel的轻量级企业集成框架设计实践,对比了两者在协议支持、消息处理能力和部署灵活性等方面的差异。通过实际代码示例和性能优化技巧,帮助开发者构建高效的核心模块,适用于现代微服务架构下的系统集成需求。

weixin_28738165的博客 374

springboot+ehcache+redis实现性能更好的一级和二级缓存

由于目前redis是主流的缓存框架。所以我们平常在想到缓存的时候,首先想到的就是用redis作为缓存。但是redis也不是完全就没有缺点。其中一个确定就是我们用redis作为缓存服务器。缓存的内容都是存在在redis服务器上。那么我们需要查询,时候从redis中命中缓存并且取出并加载到我们的内存中使用这个过程是需要网络IO的。那么就是要有性能损耗的。而且单纯用redis作为缓存服务器则要考虑缓存穿...

liyingying111111的专栏 3259

Nginx源码安装和基础配置

Nginx简介 nginx: 世界第二大web服务器软件,以高并发、低消耗著称,源自于俄罗斯,创建者 Igor(伊戈尔),2004年开源,最早以代理服务器的身份出现,2015成立nginx公司,2019年以6.7亿被F5 Networks公司收购。 代理服务器: 正向:squid 反向: squid:最古老的代理服务器 LVS: 优点: 1.抗负载能力强、是工作在网络4层之上仅作分发之用 2.配置性比较低,这是一个缺点也是一个优点,简单不易出错 3.工作稳定,抗负载能力很强,有完整的双机热备方案

hjyhjy0的博客 500

Spring Boot缓存组件Ehcache、Caffeine、Redis、Hazelcast

本文分析了Spring Boot缓存架构的核心组件与主流缓存工具特性对比。通过表格和图表详细比较了Ehcache、Caffeine、Redis和Hazelcast在性能、存储方式、集群支持等关键维度的差异,并提供了本地缓存(Caffeine)和分布式缓存(Redis)的配置实现案例。针对不同应用场景,提出技术选型决策树:小数据量高性能场景推荐Caffeine,大数据量分布式场景选择Redis或Hazelcast。最后对比了各方案的高级特性,为开发者提供全面的缓存技术选型参考。

笔记 2835

dpdk 源码分析 rte_ring

rte_ring源码分析

qq_40843445的博客 929

网页内容抓取的艺术:使用R语言解析动态网页

本文探讨了使用R语言处理动态网页数据的方法。针对AJAX加载的学术网站,传统的静态抓取和RSelenium方法存在会话终止、浏览器错误等问题。通过分析发现内容通过admin-ajax.php加载,提出使用httr2模拟POST请求获取数据,配合rvest解析HTML内容。该方法避免了浏览器自动化的弊端,实现了高效稳定的动态内容提取,为处理类似AJAX网站提供了通用解决方案。

m0_74337424的博客 52

Spring Boot2.0+Redis+Ehcache实现二级缓存

Spring Boot2.0+Redis+Ehcache实现二级缓存 EHCache 本地缓存 Redis 分布式缓存(可以共享) 一级 Redis 二级Ehcache 当redis挂了 有备胎 反之: 先走本地,本地没有再走网络 尽量少走Redis 效率会高一些 Redis与数据库的区别: 相同点 都是需要进行网络连接 不同点 是存放的介质...

art_code的博客 1192

408 | 408常用计算公式与方法 —— 计组篇 汇总

408常用计算公式与方法 —— 计算机组成原理篇 汇总

"You are worthy! You can do it!" 4649

Spring Boot All缓存策略:Redis与EhCache性能优化指南

在现代Web应用开发中,缓存是提升系统性能的关键技术之一。Spring Boot All作为一个集成了多种主流技术的开源项目,提供了Redis和EhCache两种强大的缓存解决方案。本文将详细介绍如何在Spring Boot All项目中配置和优化这两种缓存策略,帮助开发者根据实际需求选择合适的缓存方案,显著提升应用性能。 ## 为什么选择Spring Boot All的缓存方案? Sprin

gitblog_01036的博客 620

visio安装包

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

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

spring boot 使用spring cache 整合多级缓存(EhCache,Redis)

spring boot spring cache实现多级缓存,只是按照自己的思想实现,若有读者有更好的解决思路,欢迎指点spring cache实现多级缓存的思路如下:添加自定义的CacheManager,自定义的Cache,在Cache里实现多级缓存的操作(增删查)配置类如下注意红色标记的部分:package com.zyc.zspringboot.config; import com.zyc...

啊大海全是水的博客 1万+

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

Spring Boot项目里,除了Redis,我为什么还选了Ehcache 3.x做本地缓存?

本文探讨了在Spring Boot项目中结合使用Ehcache 3.x和Redis的混合缓存策略,分析了本地缓存与分布式缓存的优劣,并详细介绍了Ehcache 3.x的分层存储架构、JSR-107标准支持及企业级特性。通过实战示例展示了如何集成Ehcache 3.x到Spring Boot项目,并提供了性能调优与问题排查的建议,帮助开发者构建高性能的多级缓存系统。

weixin_30321709的博客 194

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

Spring Boot Cache缓存与Redis、Ehcache应用

缓存介绍 Spring3.1之后引入了基于注释(annotation)的缓存(cache)技术,它本质上不是一个具体的缓存实现方案(如EHCache 或者Redis),而是一个对缓存使用的抽象,通过在既有代码中添加少量它定义的各种annotation,即能够达到缓存方法的返回对象的效果。 Spring的缓存技术还具备相当的灵活性,不仅能够使用 SpEL(Spring Expression Language)来定义缓存的key和各种condition,还提供开箱即用的缓存临时存储方案,也支持和主流的专业

苏叶新城 581

Spring Boot:缓存-Ehcache和Redis

一:前言 在我们编写的应用中,组件一般都是无状态的,一个请求过来,经过逻辑处理返回所需要的结果,但下一次再来的相同请求的时候,需要再走一边流程。对于所需求的结果,我们可能需要经过计算/访问数据库/远程服务调用来获取,但对于结果变更不频繁的,做相同的事就是资源浪费。 解决方案:缓存,现在主流的缓存是Encache和Redis,我就这两个为例。 二:缓存情况说明 下列是缓存使用的时候使用的注解 ...

记录,记录,记录 420

spring data rest 缓存/spring boot Jpa 二级缓存 ehcache 与 redis

这两天都在为学校的项目做准备,期间也遇到了很多问题,比如自己写代码生成器,比如授权这些,发现自己还是有点太弱了。但是最为棘手的莫过于缓存的问题。主要原因还是自己太想用 spring data rest 了,这个在假期就没有解决缓存的问题,现在还是要来再次面对,不过相隔几个月,今非昔比。 问题分析 项目直接使用 spring data rest 进行资源暴露,repository 完全接手,所以我舍去了 service 层,controller 也基本没有方法,就算有也被抽象出来了。那么没有 servic

lgxzzz的博客 1730

【开源项目 h2cache-spring-boot-starter】自研 Starter:基于 Spring Cache 实现多级缓存(同时整合 Ehcache & Redis)

自研 Spring Boot Starter。 基于 Spring Cache 实现多级缓存。 同时使用本地缓存 Ehcache 和 分布式缓存 Redis。 实现自动化配置自定义缓存。

Howinfun的博客 1412

Spring Boot 缓存Ehcache、Redis(六)

Spring Boot 缓存技术 一、Spring Boot整合Ehcache 如果对Ehcache不了解可以查看一下文档,进行了解 1 修改 pom 文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven

m0_38075227的博客 221

Spring Boot缓存技术(ehcache、SpringData Redis)

SpringBoot 整合 Ehcache SpringBoot 整合 SpringDataRedis     一、SpringBoot 整合 Ehcache   1、导入相关maven依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001...

青衫 530

Spring Boot 使用Redis和Ehcache做拥有二级缓存的系统

上一张说到了Ehcache的简单使用,但是Ehcache一般作为本地缓存来使用,而在一个系统可能会根据服务的不用会部署在不同的机器上,那么在每一台机器都设置Ehcache,又要把一些公用的信息缓存一遍,这样不利于使用Ehcache。 而这时,我们可以再做一个缓存,这个缓存保存了一些经常使用,而且可以较大的数据。这个就是Redis。Redis已经成为了最常用的几种NoSql之一了,不仅开源,而且简单

小白杨 8801

Spring Boot 缓存实战Chapter06项目:从入门到整合 Ehcache 与 Redis

定义:查询一个不存在的数据,请求直接打到数据库。解决方案缓存空值:将 null 作为值缓存,设置较短过期时间布隆过滤器:先判断 key 是否存在,不存在则直接返回定义:某个热点数据过期瞬间,大量请求同时打到数据库。解决方案分布式锁,只让一个线程去查数据库,其他线程等待。try {// 双检锁:再次检查缓存定义大量缓存同时过期,导致请求全部涌入数据库。解决方案随机过期时间:在基础过期时间上加随机值热点数据永不过期:异步更新熔断降级:使用 Sentinel/Hystrix。

bilibligaming的博客 235
上一篇: 记一次Linux线上环境搭建
下一篇: Spring Boot中通过AOP实现统一日志解决方案
leebin_20
博客等级 码龄12年 17粉丝 28原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值