详解Spring Boot使用redis实现数据缓存

 更新时间:2017年04月17日 08:27:24   作者:小南家的青蛙  
本篇文章主要介绍了详解Spring Boot使用redis实现数据缓存,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

基于spring Boot 1.5.2.RELEASE版本,一方面验证与Redis的集成方法,另外了解使用方法。

集成方法

1、配置依赖

修改pom.xml,增加如下内容。

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

2、配置Redis

修改application.yml,增加如下内容。

spring:
  redis:
    host: localhost 
    port: 6379
    pool:
      max-idle: 8 
      min-idle: 0
      max-active: 8
      max-wait: -1

3、配置Redis缓存

package net.jackieathome.cache;

import java.lang.reflect.Method;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
@EnableCaching // 启用缓存特性
public class RedisConfig extends CachingConfigurerSupport {
  // 缓存数据时Key的生成器,可以依据业务和技术场景自行定制
// @Bean
// public KeyGenerator customizedKeyGenerator() {
//   return new KeyGenerator() {
//     @Override
//     public Object generate(Object target, Method method, Object... params) {
//       StringBuilder sb = new StringBuilder();
//       sb.append(target.getClass().getName());
//       sb.append(method.getName());
//       for (Object obj : params) {
//         sb.append(obj.toString());
//       }
//       return sb.toString();
//     }
//   };
//
// }
  // 定制缓存管理器的属性,默认提供的CacheManager对象可能不能满足需要
  // 因此建议依赖业务和技术上的需求,自行做一些扩展和定制
  @Bean
  public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
    RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
    redisCacheManager.setDefaultExpiration(300);
    return redisCacheManager;
  }

  @Bean
  public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
    StringRedisTemplate template = new StringRedisTemplate(factory);
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);
    template.setValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();
    return template;
  }
}

验证集成后的效果

考虑到未来参与的项目基于MyBatis实现数据库访问,而利用缓存,可有效改善Web页面的交互体验,因此设计了如下两个验证方案。

方案一

在访问数据库的数据对象上增加缓存注解,定义缓存策略。从测试效果看,缓存有效。

1、页面控制器

package net.jackieathome.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import net.jackieathome.bean.User;
import net.jackieathome.dao.UserDao;
import net.jackieathome.db.mapper.UserMapper;

@RestController
public class UserController {

  @Autowired
  private UserDao userDao;

  @RequestMapping(method = RequestMethod.GET, value = "/user/id/{id}")
  public User findUserById(@PathVariable("id") String id) {
    return userDao.findUserById(id);
  }

  @RequestMapping(method = RequestMethod.GET, value = "/user/create")
  public User createUser() {
    long time = System.currentTimeMillis() / 1000;

    String id = "id" + time;
    User user = new User();
    user.setId(id);
    userDao.createUser(user);

    return userDao.findUserById(id);
  }
}

2、Mapper定义

package net.jackieathome.db.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

import net.jackieathome.bean.User;


@Mapper
public interface UserMapper {

  void createUser(User user);

  User findUserById(@Param("id") String id);
}

3、数据访问对象

package net.jackieathome.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import net.jackieathome.bean.User;
import net.jackieathome.db.mapper.UserMapper;

@Component
@CacheConfig(cacheNames = "users")
@Transactional
public class UserDao {
  private static final Logger LOG = LoggerFactory.getLogger(UserDao.class);
  @Autowired
  private UserMapper userMapper;

  @CachePut(key = "#p0.id")
  public void createUser(User user) {
    userMapper.createUser(user);
    LOG.debug("create user=" + user);
  }

  @Cacheable(key = "#p0")
  public User findUserById(@Param("id") String id) {
    LOG.debug("find user=" + id);
    return userMapper.findUserById(id);
  }
}

方案二

直接在Mapper定义上增加缓存注解,控制缓存策略。从测试效果看,缓存有效,相比于方案一,测试代码更加简洁一些。

1、页面控制器

package net.jackieathome.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import net.jackieathome.bean.User;
import net.jackieathome.dao.UserDao;
import net.jackieathome.db.mapper.UserMapper;

@RestController
public class UserController {

  @Autowired
  private UserMapper userMapper;

  @RequestMapping(method = RequestMethod.GET, value = "/user/id/{id}")
  public User findUserById(@PathVariable("id") String id) {
    return userMapper.findUserById(id);
  }

  @RequestMapping(method = RequestMethod.GET, value = "/user/create")
  public User createUser() {
    long time = System.currentTimeMillis() / 1000;

    String id = "id" + time;
    User user = new User();
    user.setId(id);
    userMapper.createUser(user);

    return userMapper.findUserById(id);
  }
}

2、Mapper定义

package net.jackieathome.db.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

import net.jackieathome.bean.User;

@CacheConfig(cacheNames = "users")
@Mapper
public interface UserMapper {

  @CachePut(key = "#p0.id")
  void createUser(User user);

  @Cacheable(key = "#p0")
  User findUserById(@Param("id") String id);
}

总结

上述两个测试方案并没有优劣之分,仅是为了验证缓存的使用方法,体现了不同的控制粒度,在实际的项目开发过程中,需要依据实际情况做不同的决断。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Java后端长时间无操作自动退出的实现方式

    Java后端长时间无操作自动退出的实现方式

    这篇文章主要介绍了Java后端长时间无操作自动退出的实现方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-01-01
  • Java完整实现记事本代码

    Java完整实现记事本代码

    这篇文章主要介绍了Java实现的简易记事本,较为详细的分析了基于java实现记事本程序的完整过程,具有一定参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • IntelliJ-Idea导出可执行Jar流程解析

    IntelliJ-Idea导出可执行Jar流程解析

    这篇文章主要介绍了IntelliJ-Idea导出可执行Jar流程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-12-12
  • Jmeter逻辑控制器事务控制器使用方法解析

    Jmeter逻辑控制器事务控制器使用方法解析

    这篇文章主要介绍了Jmeter逻辑控制器事务控制器使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • 基于Java实现音乐播放器的示例代码

    基于Java实现音乐播放器的示例代码

    这篇文章主要为大家详细介绍了如何利用Java编写一个简单的音乐播放器,文中的示例代码讲解详细,具有一定的学习价值,感兴趣的小伙伴可以了解一下
    2023-07-07
  • Quarkus集成apollo配置中心

    Quarkus集成apollo配置中心

    这篇文章主要介绍了Quarkus集成apollo配置中心,文中详细的讲解了Quarkus的config构成,以及apollo集成实现,有需要的朋友可以借鉴参考下,希望能够有所帮助
    2022-02-02
  • JAVA设计模式之建造者模式原理与用法详解

    JAVA设计模式之建造者模式原理与用法详解

    这篇文章主要介绍了JAVA设计模式之建造者模式,简单说明了建造者模式的原理、组成,并结合实例形式分析了java建造者模式的定义与用法,需要的朋友可以参考下
    2017-08-08
  • java连接mysql数据库乱码的解决方法

    java连接mysql数据库乱码的解决方法

    这篇文章主要介绍通过java连接mysql数据库的时候,页面出现乱码,这里简单分享下解决方法, 需要的朋友可以参考下
    2013-05-05
  • 深入理解Java的接口与抽象类

    深入理解Java的接口与抽象类

    本文主要介绍java 的接口和抽象类,对接口和抽象类进行介绍对比,深入理解,有需要的小伙伴可以参考下
    2016-07-07
  • java中replaceAll替换圆括号实例代码

    java中replaceAll替换圆括号实例代码

    正则表达式的保留字符主要有:圆括号、方括号、花括号、竖线、横线、点号、加号、星号、反斜杆等等,下面这篇文章主要给大家介绍了关于java中replaceAll替换圆括号的相关资料,需要的朋友可以参考下
    2022-10-10

最新评论