Spring Boot整合Spring Cache及Redis过程解析

这篇文章主要介绍了Spring Boot整合Spring Cache及Redis过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1.安装redis

a.由于官方是没有Windows版的,所以我们需要下载微软开发的redis,网址:

https://github.com/MicrosoftArchive/redis/releases

b.解压后,在redis根目录打开cmd界面,输入:redis-server.exe redis.windows.conf,启动redis(关闭cmd窗口即停止)

2.使用

a.创建SpringBoot工程,选择maven依赖

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

b.配置 application.yml 配置文件

server:
 port: 8080
spring:
 # redis相关配置
 redis:
  database: 0
  host: localhost
  port: 6379
  password:
  jedis:
   pool:
    # 连接池最大连接数(使用负值表示没有限制)
    max-active: 8
    # 连接池最大阻塞等待时间(使用负值表示没有限制)
    max-wait: -1ms
    # 连接池中的最大空闲连接
    max-idle: 5
    # 连接池中的最小空闲连接
    min-idle: 0
    # 连接超时时间(毫秒)默认是2000ms
  timeout: 2000ms
 # thymeleaf热更新
 thymeleaf:
  cache: false

c.创建RedisConfig配置类

@Configuration
@EnableCaching //开启缓存
public class RedisConfig {

  /**
   * 缓存管理器
   * @param redisConnectionFactory
   * @return
   */
  @Bean
  public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    // 生成一个默认配置,通过config对象即可对缓存进行自定义配置
    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
    // 设置缓存的默认过期时间,也是使用Duration设置
    config = config.entryTtl(Duration.ofMinutes(30))
        // 设置 key为string序列化
        .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
        // 设置value为json序列化
        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()))
        // 不缓存空值
        .disableCachingNullValues();

    // 对每个缓存空间应用不同的配置
    Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
    configMap.put("userCache", config.entryTtl(Duration.ofSeconds(60)));

    // 使用自定义的缓存配置初始化一个cacheManager
    RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)
        //默认配置
        .cacheDefaults(config)
        // 特殊配置(一定要先调用该方法设置初始化的缓存名,再初始化相关的配置)
        .initialCacheNames(configMap.keySet())
        .withInitialCacheConfigurations(configMap)
        .build();
    return cacheManager;
  }

  /**
   * Redis模板类redisTemplate
   * @param factory
   * @return
   */
  @Bean
  public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(factory);
    // key采用String的序列化方式
    template.setKeySerializer(new StringRedisSerializer());
    // hash的key也采用String的序列化方式
    template.setHashKeySerializer(new StringRedisSerializer());
    // value序列化方式采用jackson
    template.setValueSerializer(jackson2JsonRedisSerializer());
    // hash的value序列化方式采用jackson
    template.setHashValueSerializer(jackson2JsonRedisSerializer());
    return template;
  }

  /**
   * json序列化
   * @return
   */
  private RedisSerializer<Object> jackson2JsonRedisSerializer() {
    //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
    Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
    //json转对象类,不设置默认的会将json转成hashmap
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    serializer.setObjectMapper(mapper);
    return serializer;
  }
}

d.创建entity实体类

public class User implements Serializable {

  private int id;
  private String userName;
  private String userPwd;

  public User(){}

  public User(int id, String userName, String userPwd) {
    this.id = id;
    this.userName = userName;
    this.userPwd = userPwd;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getUserName() {
    return userName;
  }

  public void setUserName(String userName) {
    this.userName = userName;
  }

  public String getUserPwd() {
    return userPwd;
  }

  public void setUserPwd(String userPwd) {
    this.userPwd = userPwd;
  }

}

e.创建Service

@Service
public class UserService {

  //查询:先查缓存是是否有,有则直接取缓存中数据,没有则运行方法中的代码并缓存
  @Cacheable(value = "userCache", key = "'user:' + #userId")
  public User getUser(int userId) {
    System.out.println("执行此方法,说明没有缓存");
    return new User(userId, "用户名(get)_" + userId, "密码_" + userId);
  }

  //添加:运行方法中的代码并缓存
  @CachePut(value = "userCache", key = "'user:' + #user.id")
  public User addUser(User user){
    int userId = user.getId();
    System.out.println("添加缓存");
    return new User(userId, "用户名(add)_" + userId, "密码_" + userId);
  }

  //删除:删除缓存
  @CacheEvict(value = "userCache", key = "'user:' + #userId")
  public boolean deleteUser(int userId){
    System.out.println("删除缓存");
    return true;
  }

  @Cacheable(value = "common", key = "'common:user:' + #userId")
  public User getCommonUser(int userId) {
    System.out.println("执行此方法,说明没有缓存(测试公共配置是否生效)");
    return new User(userId, "用户名(common)_" + userId, "密码_" + userId);
  }

}

f.创建Controller

@RestController
@RequestMapping("/user")
public class UserController {

  @Resource
  private UserService userService;

  @RequestMapping("/getUser")
  public User getUser(int userId) {
    return userService.getUser(userId);
  }

  @RequestMapping("/addUser")
  public User addUser(User user){
    return userService.addUser(user);
  }

  @RequestMapping("/deleteUser")
  public boolean deleteUser(int userId){
    return userService.deleteUser(userId);
  }

  @RequestMapping("/getCommonUser")
  public User getCommonUser(int userId) {
    return userService.getCommonUser(userId);
  }

}
@Controller
public class HomeController {
  //默认页面
  @RequestMapping("/")
  public String login() {
    return "test";
  }

}

g.在 templates 目录下,写书 test.html 页面

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>test</title>
  <style type="text/css">
    .row{
      margin:10px 0px;
    }
    .col{
      display: inline-block;
      margin:0px 5px;
    }
  </style>
</head>
<body>
<div>
  <h1>测试</h1>
  <div class="row">
    <label>用户ID:</label><input id="userid-input" type="text" name="userid"/>
  </div>
  <div class="row">
    <div class="col">
      <button id="getuser-btn">获取用户</button>
    </div>
    <div class="col">
      <button id="adduser-btn">添加用户</button>
    </div>
    <div class="col">
      <button id="deleteuser-btn">删除用户</button>
    </div>
    <div class="col">
      <button id="getcommonuser-btn">获取用户(common)</button>
    </div>
  </div>
  <div class="row" id="result-div"></div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
  $(function() {
    $("#getuser-btn").on("click",function(){
      var userId = $("#userid-input").val();
      $.ajax({
        url: "/user/getUser",
        data: {
          userId: userId
        },
        dataType: "json",
        success: function(data){
          $("#result-div").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]");
        },
        error: function(e){
          $("#result-div").text("系统错误!");
        },
      })
    });
    $("#adduser-btn").on("click",function(){
      var userId = $("#userid-input").val();
      $.ajax({
        url: "/user/addUser",
        data: {
          id: userId
        },
        dataType: "json",
        success: function(data){
          $("#result-div").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]");
        },
        error: function(e){
          $("#result-div").text("系统错误!");
        },
      })
    });
    $("#deleteuser-btn").on("click",function(){
      var userId = $("#userid-input").val();
      $.ajax({
        url: "/user/deleteUser",
        data: {
          userId: userId
        },
        dataType: "json",
        success: function(data){
          $("#result-div").text(data);
        },
        error: function(e){
          $("#result-div").text("系统错误!");
        },
      })
    });
    $("#getcommonuser-btn").on("click",function(){
      var userId = $("#userid-input").val();
      $.ajax({
        url: "/user/getCommonUser",
        data: {
          userId: userId
        },
        dataType: "json",
        success: function(data){
          $("#result-div").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]");
        },
        error: function(e){
          $("#result-div").text("系统错误!");
        },
      })
    });
  });
</script>
</html>

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

(0)

相关推荐

  • SpringBoot手动使用EhCache的方法示例

    SpringBoot在annotation的层面实现了数据缓存的功能,基于Spring的AOP技术.所有的缓存配置只是在annotation层面配置,像声明式事务一样. Spring定义了CacheManager和Cache接口统一不同的缓存技术.其中CacheManager是Spring提供的各种缓存技术的抽象接口.而Cache接口包含缓存的各种操作. CacheManger 针对不同的缓存技术,需要实现不同的cacheManager,Spring定义了如下的cacheManger实现. Ca

  • SpringBoot 集成 Memcached的方法示例

    Memcached 介绍 Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度.Memcached基于一个存储键/值对的hashmap.其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信. 因为 Spring Boot 没有针对 Memcached 提供对应的组建包,因此需要我们自己来集成.官方推出的 Ja

  • spring boot+spring cache实现两级缓存(redis+caffeine)

    spring boot中集成了spring cache,并有多种缓存方式的实现,如:Redis.Caffeine.JCache.EhCache等等.但如果只用一种缓存,要么会有较大的网络消耗(如Redis),要么就是内存占用太大(如Caffeine这种应用内存缓存).在很多场景下,可以结合起来实现一.二级缓存的方式,能够很大程度提高应用的处理效率. 内容说明: 缓存.两级缓存 spring cache:主要包含spring cache定义的接口方法说明和注解中的属性说明 spring boot

  • SpringBoot中Shiro缓存使用Redis、Ehcache的方法

    SpringBoot 中配置redis作为session 缓存器. 让shiro引用 本文是建立在你是使用这shiro基础之上的补充内容 第一种:Redis缓存,将数据存储到redis 并且开启session存入redis中. 引入pom <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifac

  • springboot使用GuavaCache做简单缓存处理的方法

    问题背景 实际项目碰到一个上游服务商接口有10秒的查询限制(同个账号). 项目中有一个需求是要实时统计一些数据,一个应用下可能有多个相同的账号.由于服务商接口的限制,当批量查询时,可能出现同一个账号第一次查询有数据,但第二次查询无数据的情况. 解决方案 基于以上问题,提出用缓存的过期时间来解决. 这时,可用Redis和Guava Cache来解决: 当批量查询时,同一个账号第一次查询有数据则缓存并设置过期时间10s, 后续查询时直接从缓存中取,没有再从服务商查询. 最终采用Guava Cache

  • SpringBoot加入Guava Cache实现本地缓存代码实例

    这篇文章主要介绍了SpringBoot加入Guava Cache实现本地缓存代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在pom.xml中加入guava依赖 <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version>

  • Spring boot redis cache的key的使用方法

    在数据库查询中我们往往会使用增加缓存来提高程序的性能,@Cacheable 可以方便的对数据库查询方法加缓存.本文主要来探究一下缓存使用的key. 搭建项目 数据库 mysql> select * from t_student; +----+--------+-------------+ | id | name | grade_class | +----+--------+-------------+ | 1 | Simone | 3-2 | +----+--------+-----------

  • 详解springboot整合ehcache实现缓存机制

    EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. ehcache提供了多种缓存策略,主要分为内存和磁盘两级,所以无需担心容量问题. spring-boot是一个快速的集成框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. 由于spring-boot无需任何样板化的配置文件,所以spring-boot集成一些其他框架时会有略微的

  • Spring Boot整合Spring Cache及Redis过程解析

    这篇文章主要介绍了Spring Boot整合Spring Cache及Redis过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.安装redis a.由于官方是没有Windows版的,所以我们需要下载微软开发的redis,网址: https://github.com/MicrosoftArchive/redis/releases b.解压后,在redis根目录打开cmd界面,输入:redis-server.exe redis.wind

  • Spring Boot整合Spring Data JPA过程解析

    Spring Boot整合Spring Data JPA 1)加入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> &l

  • Spring Boot整合Elasticsearch实现全文搜索引擎案例解析

    简单说,ElasticSearch(简称 ES)是搜索引擎,是结构化数据的分布式搜索引擎.Elastic Search是一个开源的,分布式,实时搜索和分析引擎.Spring Boot为Elasticsearch及Spring Data Elasticsearch提供的基于它的抽象提供了基本的配置.Spring Boot提供了一个用于聚集依赖的spring-boot-starter-data-elasticsearch 'StarterPOM'. 引入spring-boot-starter-dat

  • Spring Boot整合Spring Security简单实现登入登出从零搭建教程

    前言 Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作. 本文主要给大家介绍了关于Spring Boot整合S

  • Spring Boot整合Spring Security的示例代码

    本文讲述Spring Boot整合Spring Security在方法上使用注解实现权限控制,使用自定义UserDetailService,从MySQL中加载用户信息.使用Security自带的MD5加密,对用户密码进行加密.页面模板采用thymeleaf引擎. 源码地址:https://github.com/li5454yong/springboot-security.git 1.引入pom依赖 <parent> <groupId>org.springframework.boot

  • spring boot基于DRUID实现数据源监控过程解析

    这篇文章主要介绍了spring boot基于DRUID实现数据源监控过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 随着需求和技术的日益革新,spring boot框架是越来越流行,她也越来越多地出现在我们的项目中,当然最主要的原因还是因为spring boot构建项目实在是太爽了,构建方便,开发简单,而且效率高.今天我们并不是来专门学习spring boot项目的,我们要讲的是数据源的加密和监控,监控到好说,就是不监控也没什么问题,但

  • Spring Boot整合Spring Data Jpa代码实例

    一.Spring Data Jpa的简介 spring data:其实就是spring 提供的一个操作数据的框架.而spring data JPA 只是spring data 框架下的一个基于JPA标准操作数据的模块. spring data jpa :基于JPA的标准对数据进行操作.简化操作持久层的代码,只需要编写接口就可以,不需要写sql语句,甚至可以不用自己手动创建数据库表. 二.添加依赖 <!--添加springdatajpa的依赖--> <dependency> <

  • Spring Boot 整合持久层之Spring Data JPA

    目录 整合Spring Data JPA 1. 创建数据库 2. 创建项目 3. 数据库配置 4. 创建实体类 5. 创建 BookDao 接口 6. 创建 BookService 7. 创建 BookController 8. 测试 整合Spring Data JPA JPA (Java Persistence API)和 Spring Data 是两个范畴的概念. Hibernate 是一个 ORM 框架,JPA 则是一种ORM,JPA 和 Hibernate 的关系就像 JDBC 与 JD

  • Spring Boot整合Redis的完整步骤

    前言 实际 开发 中 缓存 处理是必须的,不可能我们每次客户端去请求一次 服务器 ,服务器每次都要去 数据库 中进行查找,为什么要使用缓存?说到底是为了提高系统的运行速度.将用户频繁访问的内容存放在离用户最近,访问速度最 快的 地方,提高用户的响 应速度,今天先来讲下在 springboot 中整合 redis 的详细步骤. 一.Spring Boot对Redis的支持 Spring对Redis的支持是使用Spring Data Redis来实现的,一般使用Jedis或者lettuce(默认),

随机推荐