基于springboot2.x 整合 Redis的实战

基于springboot2.x 整合 Redis的实战

1. 首先,我们需要在pom.xml文件中添加Redis依赖:

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

2. 接下来,在application.properties文件中添加Redis连接信息:

# Redis连接信息
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=

3. 创建一个Redis配置类,用于创建RedisTemplate:

@Configuration
public class RedisConfig {
   @Bean
   public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
       RedisTemplate<String, Object> template = new RedisTemplate<>();
       template.setConnectionFactory(redisConnectionFactory);
       template.setKeySerializer(new StringRedisSerializer());
       template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
       template.setHashKeySerializer(new StringRedisSerializer());
       template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
       template.afterPropertiesSet();
       return template;
   }
}

4. 创建一个RedisUtil类,用于封装Redis操作:

@Component
public class RedisUtil {
   @Autowired
   private RedisTemplate<String, Object> redisTemplate;
   
   /**
    * 添加key-value
    * @param key
    * @param value
    */
   public void set(String key, Object value) {
       redisTemplate.opsForValue().set(key, value);
   }
   
   /**
    * 获取value
    * @param key
    * @return
    */
   public Object get(String key) {
       return redisTemplate.opsForValue().get(key);
   }
   
   /**
    * 删除key-value
    * @param key
    */
   public void delete(String key) {
       redisTemplate.delete(key);
   }
}

5. 在Controller中使用RedisUtil类:

@RestController
@RequestMapping("/blog")
public class BlogController {
   @Autowired
   private RedisUtil redisUtil;
   
   @GetMapping("/{id}")
   public Blog getBlog(@PathVariable Long id) {
       Blog blog = (Blog) redisUtil.get("blog_" + id);
       if (blog == null) {
           // 从数据库中查询Blog
           blog = blogService.findById(id);
           if (blog != null) {
               // 将Blog保存到Redis中
               redisUtil.set("blog_" + id, blog);
           }
       }
       return blog;
   }
}

6. 这样,我们就成功地实现了基于Spring Boot 2.x的Redis实战博客。现在,每次获取博客时,都会先从Redis中查询,如果Redis中没有,则从数据库中查询,并将结果保存到Redis中。这样可以大大提高博客访问速度,并减少数据库访问次数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

疯狂 de 程序员

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

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

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

打赏作者

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

抵扣说明:

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

余额充值