本篇文章分享的就是spring boot中的一个轮子,spring cache注解的方式实现接口数据缓存。默认的配置想非常简单,但是有一个弊端是缓存数据为永久缓存,本次将介绍如何设置接口缓存数据的过期时间
使用redis进行缓存数据,是目前比较常用的缓存解决方案。常用的缓存形式有一下几种:
1.纯原生代码进行redis的增删改查,手工编写缓存工具类,由开发者在代码中进行调用。
优势:代码由实际使用的开发者进行维护,便于定制化的改造。
2.使用市场上已有的缓存工具,也就是大家常说的大佬的轮子
优势:方便快捷,提升开发效率
目录
修改pom文件引入如下配置
<?xml version="1.0" encoding="UTF-8"?>
<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.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.test</groupId>
<artifactId>common-project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>common-project</name>
<description></description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.7</version>
</dependency>
</dependencies>
</project>
application.yml中增加redisd 配置信息
spring:
redis:
host: localhost
port: 6379
database: 0
password: *****
timeout: 10000
server:
port: 8082
在spring 3.1版本以后,注意是spring的版本,不是spring boot的版本。在spring-context包中合并进去了spring Cache的内容。可以使用注解方式进行缓存设定。
开启缓存只需要在入口函数上增加@EnableCaching注解
@SpringBootApplication
@EnableCaching //开启缓存
public class CommonApplication {
public static void main(String[] args) {
SpringApplication.run(CommonApplication.class,args);
}
}
设置缓存空间可能大家不好理解,换一个通俗的说法就是设置要缓存的类,把这个类下面要缓存的数据的key加上一个统一的前缀,也是一个注解:@CacheConfig这里可以设置具体的值如下
@RestController
@RequestMapping("/test")
@CacheConfig(cacheNames = "test-controller")
public class TestController {
@Autowired
TestService testService;
@RequestMapping("/testCache")
@Cacheable(key = "'testCache'",unless = "#result==null")
public Object testCache(){
return testService.getUserInfoList();
}
}
这里的cacheNames就是我上面说的缓存空间,也许这样还是没办法理解,请看在redis中的缓存情况:

就是说如果我在 TestController类下设置的接口缓存数据都会缓存到test-controller这个缓存空间里。
这里就是指具体要缓存的接口数据,使用注解:@Cacheable,具体代码参见上面的代码块。
截止到这里,就可以启动服务,调用接口,会发现数据已经可以缓存到redis中了。但是,这里有一个问题,就是缓存下来的数据,是永久缓存,一旦接口实际的数据有更新,只能通过再设置更新方法来更新缓存,或者删除缓存,我们都知道redis本身是支持设置key的过期时间的,这一特性,让缓存变得更加优雅,所以我们的程序也要有!!!
想要设置缓存过期时间,也并不是很麻烦,只是需要单独增加一个redis的配置类,自定义修改一下缓存管理器就可以了
@Configuration
public class RedisCacheManagerConfig {
/**
* redis模板配置以及序列化配置
*
* @param factory 工厂
* @return {@link RedisTemplate}<{@link String}, {@link Object}>
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//key 采用的String 的序列化方式
template.setKeySerializer(stringRedisSerializer);
//hashde key 也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
//value 序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
//hash 的 value序列化方式采用jackson
template.setHashKeySerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
template.afterPropertiesSet();
return template;
}
@Bean
RedisCacheWriter writer(RedisTemplate<String, Object> redisTemplate) {
return RedisCacheWriter.nonLockingRedisCacheWriter(Objects.requireNonNull(redisTemplate.getConnectionFactory()));
}
@Bean
CacheManager cacheManager(RedisCacheWriter writer) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
Map<String, RedisCacheConfiguration> configurationMap = new HashMap<>();
// 配置序列化(解决乱码的问题)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1))//time
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
//此处可以自定义缓存空间的缓存的过期时间,可以根据自己实际情况进行设置,也可以不设置,用统一过期时间
configurationMap.put("test-controller", config.entryTtl(Duration.ofSeconds(200)));
//解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
return RedisCacheManager.builder(writer)
.initialCacheNames(configurationMap.keySet())
.withInitialCacheConfigurations(configurationMap)
//其他缓存空间缓存过期时间为500S
.cacheDefaults(config.entryTtl(Duration.ofSeconds(500)))
.build();
}
}
增加了此配置类之后,之前的代码均不需要更改,直接启动程序,测试验证,可以看到redis中的数据是被设置了过期时间的

此处可能会有个意外惊喜(小坑):就是直接启动程序后,调用接口报错,提示json格式转换异常,这里是由于先前直接用的默认的redisTemplate,value的反序列化问题,可以将之前缓存的数据清理一下,再重新调用就可以了。
注解方式进行接口数据缓存,在实际项目开发过程中比较常见,我分享的这种方式也是大家比较常用的一种方式,配置简单,开发成本低,使用方便。只需要:
这里题外记录一下缓存注解中的一下参数含义及用法

另外设置缓存的注解中支持spEL表达式,下面是一些可用的表达式含义

我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass
我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击
我想设置一个默认日期,例如实际日期,我该如何设置?还有如何在组合框中设置默认值顺便问一下,date_field_tag和date_field之间有什么区别? 最佳答案 试试这个:将默认日期作为第二个参数传递。youcorrectlysetthedefaultvalueofcomboboxasshowninyourquestion. 关于ruby-on-rails-date_field_tag,如何设置默认日期?[rails上的ruby],我们在StackOverflow上找到一个类似的问
我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查
这个问题在这里已经有了答案:Railsformattingdate(4个答案)关闭4年前。我想格式化Time.Now函数以显示YYYY-MM-DDHH:MM:SS而不是:“2018-03-0909:47:19+0000”该函数需要放在时间中.现在功能。require‘roo’require‘roo-xls’require‘byebug’file_name=ARGV.first||“Template.xlsx”excel_file=Roo::Spreadsheet.open(“./#{file_name}“,extension::xlsx)xml=Nokogiri::XML::Build
我试过重新启动apache,缓存的页面仍然出现,所以一定有一个文件夹在某个地方。我没有“公共(public)/缓存”,那么我还应该查看哪些其他地方?是否有一个URL标志也可以触发此效果? 最佳答案 您需要触摸一个文件才能清除phusion,例如:touch/webapps/mycook/tmp/restart.txt参见docs 关于ruby-如何在Ubuntu中清除RubyPhusionPassenger的缓存?,我们在StackOverflow上找到一个类似的问题:
我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s
我正在玩HTML5视频并且在ERB中有以下片段:mp4视频从在我的开发环境中运行的服务器很好地流式传输到chrome。然而firefox显示带有海报图像的视频播放器,但带有一个大X。问题似乎是mongrel不确定ogv扩展的mime类型,并且只返回text/plain,如curl所示:$curl-Ihttp://0.0.0.0:3000/pr6.ogvHTTP/1.1200OKConnection:closeDate:Mon,19Apr201012:33:50GMTLast-Modified:Sun,18Apr201012:46:07GMTContent-Type:text/plain
尝试在我的RoR应用程序中实现计数器缓存列时出现错误Unknownkey(s):counter_cache。我在这个问题中实现了模型关联:Modelassociationquestion这是我的迁移:classAddVideoVotesCountToVideos0Video.reset_column_informationVideo.find(:all).eachdo|p|p.update_attributes:videos_votes_count,p.video_votes.lengthendenddefself.downremove_column:videos,:video_vot