SpringBoot使用Redis缓存MySql的方法步骤

 更新时间:2022年02月22日 11:05:54   作者:lanxing_thk  
本文主要介绍了SpringBoot使用Redis缓存MySql的方法步骤,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

1 项目组成

  • 应用:springboot rest api
  • 数据库:mysql
  • jdbc框架:jpa
  • 缓存中间件:redis

2 运行springboot

2.1 官网download最基本的restful应用

教程地址:https://spring.io/guides/gs/rest-service/

直接download成品,找到git命令 :git clone https://github.com/spring-guides/gs-rest-service.git

创建一个文件夹,打开git bash here(安装git)

在这里插入图片描述

Idea打开成品 (complete文件夹)

在这里插入图片描述

2.2 运行应用

gradle -> bootRun右键 -> Run/Deubg

在这里插入图片描述

通过http://localhost:8080/greeting?name=lanxingisthebest访问

3 访问mysql

增加gradle依赖 (通过jpa)

implementation(‘mysql:mysql-connector-java')
implementation(‘org.springframework.boot:spring-boot-starter-data-jpa')

增加配置文件及数据库配置

创建文件application.yml

在这里插入图片描述

spring:
 datasource:
   url: jdbc:mysql://localhost:3306/user_info
   username: root
   password: root
 jpa:
   show-sql: true

类调整

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

mysql insert一条数据,然后通过 http://localhost:8080/listAllUser 查询数据库

4 设置redis缓存

增加gradle依赖

implementation(‘org.springframework.boot:spring-boot-starter-data-redis')
implementation(‘org.springframework.boot:spring-boot-starter-cache')

配置文件配置redis参数

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/user_info
    username: root
    password: root
  jpa:
    show-sql: true
  ## Redis 配置
  redis:
    ## Redis数据库索引(默认为0)
    database: 0
    ## Redis服务器地址
    host: localhost
    ## Redis服务器连接端口
    port: 6379
    ## Redis服务器连接密码(默认为空)
    password:
    jedis:
      pool:
        ## 连接池最大连接数(使用负值表示没有限制)
        #spring.redis.pool.max-active=8
        max-active: 8
        ## 连接池最大阻塞等待时间(使用负值表示没有限制)
        #spring.redis.pool.max-wait=-1
        max-wait: -1
        ## 连接池中的最大空闲连接
        #spring.redis.pool.max-idle=8
        max-idle: 8
        ## 连接池中的最小空闲连接
        #spring.redis.pool.min-idle=0
        min-idle: 0
    ## 连接超时时间(毫秒)
    timeout: 1200

Redis配置类

在这里插入图片描述

RedisConfig代码

package com.example.restservice.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * @author lzh
 * create 2019-09-24-15:07
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 选择redis作为默认缓存工具
     * @param redisConnectionFactory
     * @return
     */
    /*@Bean
    //springboot 1.xx
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        return rcm;
    }*/
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1)); // 设置缓存有效期一小时
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }

    /**
     * retemplate相关配置
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }

    /**
     * 对hash类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    /**
     * 对redis字符串类型数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    /**
     * 对链表类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    /**
     * 对无序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    /**
     * 对有序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
}

代码通过@Cacheable使用 redis缓存

在这里插入图片描述

访问接口后,通过redis工具查询数据

点击 redis-lic.exe
命令 keys *

在这里插入图片描述

 到此这篇关于SpringBoot使用Redis缓存MySql的方法步骤的文章就介绍到这了,更多相关SpringBoot Redis缓存MySql内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java实现XML与JSON的互相转换详解

    Java实现XML与JSON的互相转换详解

    这篇文章主要为大家详细介绍了如何使用Java实现XML与JSON的互相转换,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2025-03-03
  • Java 实战项目锤炼之小区物业管理系统的实现流程

    Java 实战项目锤炼之小区物业管理系统的实现流程

    读万卷书不如行万里路,只学书上的理论是远远不够的,只有在实战中才能获得能力的提升,本篇文章手把手带你用java+SSM+jsp+mysql+maven实现一个小区物业管理系统,大家可以在过程中查缺补漏,提升水平
    2021-11-11
  • java中Memcached的使用实例(包括与Spring整合)

    java中Memcached的使用实例(包括与Spring整合)

    这篇文章主要介绍了java中Memcached的使用实例(包括与Spring整合),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • Java中拼接字符串String的N种方法总结

    Java中拼接字符串String的N种方法总结

    字符串拼接是我们在Java代码中比较经常要做的事情,就是把多个字符串拼接到一起,下面这篇文章主要给大家介绍了关于Java中拼接String的N种方法,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2022-02-02
  • MyBatis二级缓存实现关联刷新

    MyBatis二级缓存实现关联刷新

    本文主要介绍了MyBatis二级缓存实现关联刷新,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-01-01
  • 基于Java事件监听编写一个中秋猜灯谜小游戏

    基于Java事件监听编写一个中秋猜灯谜小游戏

    众所周知,JavaSwing是Java中关于窗口开发的一个工具包,可以开发一些窗口程序,然后由于工具包的一些限制,导致Java在窗口开发商并没有太多优势,不过,在JavaSwing中关于事件的监听机制是我们需要重点掌握的内容,本文将基于Java事件监听编写一个中秋猜灯谜小游戏
    2023-09-09
  • SpringBoot(十)之邮件服务

    SpringBoot(十)之邮件服务

    这篇文章给大家介绍了SpringBoot邮件服务的相关知识,此文是使用springboot最新版本1.5.3进行开发的。本文给大家介绍的非常详细,具有参考借鉴价值,需要的的朋友参考下吧
    2017-05-05
  • JavaScript中栈和队列应用详情

    JavaScript中栈和队列应用详情

    这篇文章主要介绍了JavaScript中栈和队列应用详情,栈如果用数组模拟的话是类似于一个U形桶状堆栈空间,文章围绕制图展开详细的内容展开更多相关内容,需要的小伙伴可以参考一下
    2022-06-06
  • IDEA Maven下载依赖包速度过慢的问题及解决方案

    IDEA Maven下载依赖包速度过慢的问题及解决方案

    这篇文章主要介绍了IDEA Maven下载依赖包速度过慢的问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09
  • 用java实现的获取优酷等视频缩略图的实现代码

    用java实现的获取优酷等视频缩略图的实现代码

    想获取优酷等视频缩略图,在网上没有找到满意的资料,参考了huangdijia的PHP版工具一些思路,写了下面的JAVA版代码。。其实也可以做成JS版的
    2013-05-05

最新评论