• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >Java > 详解Spring Boot使用redis实现数据缓存

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

作者:小南家的青蛙 字体:[增加 减小] 来源:互联网 时间:2017-05-28

小南家的青蛙 通过本文主要向大家介绍了spring boot注解详解,spring boot详解,spring配置文件详解,spring注解详解,spring aop详解等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

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

集成方法

1、配置依赖

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

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

2、配置Redis

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

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

</div>

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;
  }
}

</div>

验证集成后的效果

考虑到未来参与的项目基于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);
  }
}

</div>

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

</div>

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

</div>

方案二

直接在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()



 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • 详解Spring boot上配置与使用mybatis plus
  • 详解Spring Boot中Controller用法
  • 详解Spring Boot 定时任务的实现方法
  • 详解在Spring Boot中使用数据库事务
  • spring boot整合CAS配置详解
  • Spring Boot Redis 集成配置详解
  • 详解Spring Boot集成MyBatis(注解方式)
  • Spring Boot的Profile配置详解
  • 详解spring boot配置 ssl
  • spring boot 的常用注解使用小结

相关文章

  • 2017-05-28初识Spring Boot框架之Spring Boot的自动配置
  • 2017-05-28Spring中配置和读取多个Properties文件的方式方法
  • 2017-05-28详谈java中boolean和Boolean的区别
  • 2017-05-28Spring2.5.6开发环境搭建图文教程
  • 2017-05-28详解java枚举用法及实例
  • 2017-05-28Java通过Fork/Join优化并行计算
  • 2017-05-28详解Spring整合Quartz实现动态定时任务
  • 2017-05-28java用重定向方法从文件中读入或写入数据
  • 2017-05-28Java SpringMVC实现国际化整合案例分析(i18n)
  • 2017-05-28详解Spring boot+CXF开发WebService Demo

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • springboot + swagger 实例代码
    • Java实现在不同线程中运行的代码实例
    • 认证流程源码级详解
    • java中的connection reset 异常处理分析
    • Spring Task定时任务的配置和使用详解
    • javaweb分页原理详解
    • java中&与&&的区别
    • Spring Session实现分布式session的简单示例
    • 老生常谈JVM的内存溢出说明及参数调整
    • springboot集成mybatis实例代码

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有