Spring 整合redis-注解式缓存使用配置

一、 redis连接属性文件redis.properties

redis.host=127.0.0.1
redis.port=6379
redis.pool.maxTotal=105
redis.pool.maxIdle=10
redis.pool.maxWaitMillis=5000
redis.pool.testOnBorrow=true

二、spring-redis.xml

  1. 加载redis.properties中属性
<context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true"/>

如果在这里遇到了加载属性文件错误或者找不到的问题,或者还会出现dataSource加载失败的问题,遇到这些问题时建议看我上一篇文章《spring配置中的context:property-placeholder》[https://blog.csdn.net/fenfei_zqh/article/details/82423541]

  1. jedisPool配置
<bean id="jedisPoolConfig" class
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,以下是一个简单的 Spring Redis 缓存注解: ```java @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface RedisCache { String key() default ""; // 缓存键值 String field() default ""; // 缓存字段,用于 Hash long expire() default 60; // 缓存过期时间,默认60秒 Class<?> type() default Object.class; // 缓存对象类型,默认为 Object 类型 } ``` 注解的作用是将方法的执行结果缓存Redis 中,下次执行方法时可以直接从缓存中获取结果,避免重复计算。 使用示例: ```java @Service public class MyService { @Autowired private RedisTemplate<String, Object> redisTemplate; @RedisCache(key = "myKey", expire = 300) public Object getData(String param1, int param2) { // 从数据库或其他服务获取数据 Object data = getDataFromOtherService(param1, param2); return data; } private Object getDataFromOtherService(String param1, int param2) { // ... } } ``` 在上面的例子中,`MyService` 的 `getData` 方法被加上了 `@RedisCache` 注解,表示该方法的执行结果需要缓存Redis 中。`key` 参数指定了缓存的键值,这里设置为 `myKey`,`expire` 参数指定了缓存的过期时间,这里设置为 300 秒(即 5 分钟)。当 `getData` 方法第一次被调用时,会先从 Redis 中查询缓存,如果缓存中没有对应的结果,则执行 `getDataFromOtherService` 方法获取数据,并将结果缓存Redis 中。下次再调用 `getData` 方法时,会直接从 Redis 中获取缓存结果。 需要注意的是,使用 Redis 缓存需要先配置 RedisTemplate,这里省略了配置代码。另外,该注解只适用于方法返回值为 Object 类型的情况,如果要支持其他类型的返回值,需要修改注解中的 `type` 参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值