全网整合营销服务商

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

免费咨询热线: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 


相关文章: 制作网站公司那家好,网络公司是做什么的?  模具网站制作流程,如何找模具客户?  如何在服务器上三步完成建站并提升流量?  百度网页制作网站有哪些,谁能告诉我百度网站是怎么联系?  定制建站模板如何实现SEO优化与智能系统配置?18字教程  设计网站制作公司有哪些,制作网页教程?  常州企业网站制作公司,全国继续教育网怎么登录?  如何在VPS电脑上快速搭建网站?  如何通过FTP空间快速搭建安全高效网站?  建站IDE高效指南:快速搭建+SEO优化+自适应模板全解析  个人摄影网站制作流程,摄影爱好者都去什么网站?  如何在腾讯云免费申请建站?  学校为何禁止电信移动建设网站?  一键制作网站软件下载安装,一键自动采集网页文档制作步骤?  如何选购建站域名与空间?自助平台全解析  网站制作新手教程,新手建设一个网站需要注意些什么?  ui设计制作网站有哪些,手机UI设计网址吗?  如何在宝塔面板创建新站点?  建站之星如何配置系统实现高效建站?  网站设计制作公司地址,网站建设比较好的公司都有哪些?  南宁网站建设制作定制,南宁网站建设可以定制吗?  如何彻底卸载建站之星软件?  北京营销型网站制作公司,可以用python做一个营销推广网站吗?  制作假网页,招聘网的薪资待遇,会有靠谱的吗?一面试又各种折扣?  岳西云建站教程与模板下载_一站式快速建站系统操作指南  阿里云高弹*务器配置方案|支持分布式架构与多节点部署  建站168自助建站系统:快速模板定制与SEO优化指南  如何通过多用户协作模板快速搭建高效企业网站?  如何在Golang中引入测试模块_Golang测试包导入与使用实践  建站之星如何防范黑客攻击与数据泄露?  ,石家庄四十八中学官网?  seo网站制作优化,网站SEO优化步骤有哪些?  如何快速搭建自助建站会员专属系统?  攀枝花网站建设,攀枝花营业执照网上怎么年审?  如何在阿里云虚拟主机上快速搭建个人网站?  大同网页,大同瑞慈医院官网?  建站之星如何优化SEO以实现高效排名?  如何快速重置建站主机并恢复默认配置?  如何解决VPS建站LNMP环境配置常见问题?  如何通过商城免费建站系统源码自定义网站主题?  nginx修改上传文件大小限制的方法  专业网站制作服务公司,有哪些网站可以免费发布招聘信息?  英语简历制作免费网站推荐,如何将简历翻译成英文?  建站主机解析:虚拟主机配置与服务器选择指南  如何快速搭建高效简练网站?  矢量图网站制作软件,用千图网的一张矢量图做公司app首页,该网站并未说明版权等问题,这样做算不算侵权?应该如何解决?  电商网站制作多少钱一个,电子商务公司的网站制作费用计入什么科目?  建站VPS选购需注意哪些关键参数?  C++如何编写函数模板?(泛型编程入门)  如何用已有域名快速搭建网站? 

您的项目需求

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