全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

详解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);
}

总结

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

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


# springboot  # redis缓存  # springboot集成redis  # spring  # Spring Boot中使用Redis做缓存的方法实例  # SpringBoot使用Redis缓存的实现方法  # 浅谈Spring Boot中Redis缓存还能这么用  # SpringBoot Redis缓存数据实现解析  # SpringBoot 开启Redis缓存及使用方法  # springBoot整合redis做缓存具体操作步骤  # 考虑到  # 仅是  # 实际情况  # 管理器  # 技术上  # 之分  # 大家多多  # 过程中  # 未来  # 体现了  # 在实际  # RedisTemplate  # StringRedisTemplate  # RedisConnectionFactory  # core  # serializer  # jackson  # context  # Jackson2JsonRedisSerializer  # fasterxml 


相关文章: Python文件管理规范_工程实践说明【指导】  如何通过IIS搭建网站并配置访问权限?  如何高效配置IIS服务器搭建网站?  如何批量查询域名的建站时间记录?  如何在橙子建站上传落地页?操作指南详解  php能控制zigbee模块吗_php通过串口与cc2530 zigbee通信【介绍】  Python lxml的etree和ElementTree有什么区别  微信推文制作网站有哪些,怎么做微信推文,急?  如何选择高效稳定的ISP建站解决方案?  外汇网站制作流程,如何在工商银行网站上做外汇买卖?  建站之星如何取消后台验证码生成?  制作网站的公司有哪些,做一个公司网站要多少钱?  建站之星安装后如何自定义网站颜色与字体?  ,交易猫的商品怎么发布到网站上去?  如何通过老薛主机一键快速建站?  如何确保西部建站助手FTP传输的安全性?  C++用Dijkstra(迪杰斯特拉)算法求最短路径  如何在Ubuntu系统下快速搭建WordPress个人网站?  重庆市网站制作公司,重庆招聘网站哪个好?  如何选择适合PHP云建站的开源框架?  如何快速搭建自助建站会员专属系统?  大连网站制作公司哪家好一点,大连买房网站哪个好?  如何通过.red域名打造高辨识度品牌网站?  建站之星安全性能如何?防护体系能否抵御黑客入侵?  如何用PHP快速搭建CMS系统?  如何在云虚拟主机上快速搭建个人网站?  网站制作公司,橙子建站是合法的吗?  建站一年半SEO优化实战指南:核心词挖掘与长尾流量提升策略  如何通过建站之星自助学习解决操作问题?  如何设计高效校园网站?  如何自定义建站之星模板颜色并下载新样式?  建站之星微信建站一键生成小程序+多端营销系统  建站之星伪静态规则如何正确配置?  定制建站策划方案_专业建站与网站建设方案一站式指南  如何在新浪SAE免费搭建个人博客?  香港服务器部署网站为何提示未备案?  ,sp开头的版面叫什么?  如何在服务器上配置二级域名建站?  长沙企业网站制作哪家好,长沙水业集团官方网站?  深圳 网站制作,深圳招聘网站哪个比较好一点啊?  C++如何使用std::optional?(处理可选值)  如何彻底卸载建站之星软件?  设计网站制作公司有哪些,制作网页教程?  如何生成腾讯云建站专用兑换码?  全景视频制作网站有哪些,全景图怎么做成网页?  如何快速搭建高效可靠的建站解决方案?  山东云建站价格为何差异显著?  建站之星备案流程有哪些注意事项?  大型企业网站制作流程,做网站需要注册公司吗?  如何用wdcp快速搭建高效网站? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。