Spring与Redis集成

本文介绍了如何从使用Jedis操作Redis到引入SpringDataRedis的RedisTemplate进行简化,以及如何利用SpringCache和AOP实现注解式缓存,提高代码可读性和性能管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.引入RedisTemplate

据以前的情况,我们在Java中使用Redis时一般是使用Jedis来操作的,大致的一段代码如下所示

    @Override
    public User findUserById(Integer id) {
        User user = null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String userStr = jedis.get("user_" + id); // 尝试获取数据
            if (userStr != null && !userStr.isEmpty()) { // 如果获取到有效数据,则转换后返回
                user = JSONObject.parseObject(userStr, User.class);
            } else {// 如果没有获取到数据,则查询数据库返回
                user = userMapper.findUserById(id);
                if (user != null) jedis.set("user_" + id, JSONObject.toJSONString(user)); // 设置到redis中
            }
        } finally {
            // 记得关闭Jedis,因为这里使用的是JedisPool,所以这里的关闭并不是直接关闭连接,而是释放,以供其他的业务使用
            if (jedis != null) jedis.close();
        }
        return user;
    }

上边的这样的一段代码其实是有些臃肿的,但是如果我们引入RedisTemplate,其实会简化不少。

  • maven 引入 spring-data-redis
  <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.9.0</version>
  </dependency>
  <dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>2.2.13.RELEASE</version>
  </dependency>
  • 将RedisTemplate 加入Bean容器中,让Spring进行管理。
  @Bean
  public RedisConnectionFactory redisConnectionFactory() {
      RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
      redisStandaloneConfiguration.setHostName(host);
      redisStandaloneConfiguration.setPort(port);

      RedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration);
      return redisConnectionFactory;
  }

  @Bean
  public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
      RedisTemplate redisTemplate = new RedisTemplate();
      redisTemplate.setConnectionFactory(redisConnectionFactory);
      //设置key值的序列化方式,默认是JDK的形式
      redisTemplate.setKeySerializer(StringRedisSerializer.UTF_8);
      return redisTemplate;
  }
  • 如果使用RedisTemplate的替换的话,会简洁很多。
  @Autowired
  private RedisTemplate redisTemplate;

  @Override
  public User findUserById(Integer id) {
      Object result = redisTemplate.opsForValue().get("user_" + id);
      if (result != null) return (User) result;

      User user = userMapper.findUserById(id);
      // 设置到redis中
      if (user != null) redisTemplate.opsForValue().set("user_" + id, user);

      return user;
  }
  • 大概看一下关于RedisTemplate的方法

看了以上的内容,可以看到引入了RedisTemplate其实已经很简洁了,但是明显还不够,下面我们将考虑引入 “注解”


2. 引入注解

  • 开启缓存 @EnableCaching
  
@Configuration  
@EnableCaching  
public class AppConfig {
   
...
} 
  • 引入@Cacheable,表示这个方法将会访问缓存,如果无法命中缓存的话,会将方法返回的值存入redis,假设有注解为 @Cacheable(value="user", key = "#id"),那么生成的key值为 user::{id},即如果id为1 那么生成的 key就是 user::1
@Override
@Cacheable(value="user", key = "#id")
// 这里返回的值会被存放到redis,key-value格式,其中生成的key值(假设id为1): user::1
public User findUserById(Integer id) {
   
User user = userMapper.findUserById(id);
return user;
}

但是这样还不够,因为Spring并不清楚缓存的方式是什么,这就涉及到CacheManager

  • 设置CacheManager,在AppConfig中加入以下内容
@Bean
public RedisConnectionFactory redisConnectionFactory() {
   
    RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
    redisStandaloneConfiguration.setHostName(host); // 这里是redis的ip
    redisStandaloneConfiguration.setPort(port);// 这里是redis的端口

    // 自适应集群变化
    RedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration);
    return redisConnectionFactory;
}

@Bean
public RedisCacheConfiguration redisCacheConfiguration() {
   
    RedisCacheConfiguration redisCacheConfiguration 
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一杯可乐、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值