使用Spring Data + Redis实现缓存

本文展示了如何在Spring应用中使用Spring Data和Redis实现缓存功能。通过注解`@Cacheable`实现方法级缓存,并配置`JedisConnectionFactory`、`RedisTemplate`和`RedisCacheManager`来连接并管理Redis缓存。代码示例中,当方法参数`name`为'Joshua'时,结果将被缓存。客户端调用代码演示了缓存的使用和效果。
摘要由CSDN通过智能技术生成

首先,我们给一个服务配置Cache,如下:

@Service('helloService')
public class HelloServiceImpl implements HelloService {

    /**
     * Using SpEL for conditional caching - only cache method executions when
     * the name is equal to 'Joshua'
     */
    @Cacheable(value='messageCache', condition=''Joshua'.equals(#name)')
    public String getMessage(String name) {
        System.out.println('Executing HelloServiceImpl' +
                        '.getHelloMessage(\'' + name + '\')');

        return 'Hello ' + name + '!';
    }

}

使用 Jedis 作为Redis的Java客户端,在Spring只要配置三个:

JedisConnectionFactory 有以下参数:

  • hostName=”localhost”
  • port=6379
  • timeout=2000 ms
  • database=0
  • usePool=true

 

RedisTemplate是提供你使用连接池连接,使用JdkSerializationRedisSerializer序列化。

RedisCacheManager 是依赖

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值