Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >Spring Boot整合 NoSQL 数据库 Redis

Spring Boot整合 NoSQL 数据库 Redis

作者头像
百思不得小赵
发布于 2022-12-01 06:53:57
发布于 2022-12-01 06:53:57
45200
代码可运行
举报
文章被收录于专栏:小赵Java总结小赵Java总结
运行总次数:0
代码可运行

📢 专栏推荐:Spring Boot整合第三方组件 📖系列文章:【快速上手】使用SpringBoot 2.X + Mybatis-Plus 轻松实现CRUD(持续更新。。。) 🌲专栏简介: 在日常实际的开发中,我们会使用企业级快速构建项目框架Spring Boot整和 各个组件进行开发,本专栏将总结使用Spring Boot与常用第三方组件进行整合的详细步骤,欢迎大佬们交流学习。👏👏👏

文章目录

在日常的开发中,除了使用Spring Boot这个企业级快速构建项目的框架之外,随着业务数据量的大幅度增加,对元数据库造成的压力成倍剧增。在此背景下,Redis这个NoSQL数据库已然整个项目架构中的不可或缺的一部分,懂得如何Spring Boot整合 Redis,是当今开发人员必备的一项技能,接下来对整合步骤进行详细说明。

一、环境准备

在开始开发之前,我们需要准备一些环境配置:

  • jdk 1.8 或其他更高版本
  • 开发工具 IDEA
  • 管理依赖 Maven
  • Redis环境,推荐linux系统中搭建redis环境

二、构建Spring Boot项目

打开idea -> file -> Nwe -> Project ,如图,勾选填写相关的配置信息:

勾选一些初始化的依赖配置:

Spring Boot项目初始化完成。

三、引入Redis依赖

构建完成Spring Boot项目工程之后,需要在pom.xml文件中引入redis相关依赖

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<!-- redis -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- spring2.X集成redis所需common-pool2-->
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-pool2</artifactId>
	<version>2.6.0</version>
</dependency>

四、Reds相关配置

将redis相关的依赖引入到项目中之后,需要对redis进行一些配置,在application.properties配置redis:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# Redis服务器地址
spring.redis.host=自己搭建的redis服务器的 IP
# Redis服务器连接端口
spring.redis.port=6379
# Redis数据库索引(默认为0)
spring.redis.database= 0
# 连接超时时间(毫秒)
spring.redis.timeout=1800000
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=20
# 最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=5
# 连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0

五、添加Redis配置类

对Redis相关配置完成后,添加Redis配置类,(拿来即用):

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package com.zhao.demo.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.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * @author xiaoZhao
 * @date 2022/9/6
 * @describe
 */
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

六、测试一下

将所有的环境依赖和配置搭建完成之后,进行测试一把。

① 首先,确保安装Redis服务器已经启动Redis服务

② 编写controller类,前提需要引入Spring Boot Web 的依赖:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package com.zhao.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xiaoZhao
 * @date 2022/9/6
 * @describe
 */
@RestController
@RequestMapping("/redistest")
public class RedisTestController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping
    public String testRedis(){
        // 设置值到reids
        redisTemplate.opsForValue().set("name","jack");
        // 从redis中获取值
        String name = (String)redisTemplate.opsForValue().get("name");
        return name;
    }
}

③ 启动Spring Boot工程,在浏览器上向接口发送请求:

项目启动成功,向/redistest接口发送请求

请求发送成功,获取到数据,测试成功,至此Spring Boot整合 Redis所有步骤已经完成,

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-09-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Spring Boot 整合 Redis
因为首页接口对应获取的首页数据变化不大,但访问量较大,所以就有必要将首页接口数据缓存到redis缓存中,减少数据库压力和提高访问速度
FHAdmin
2022/03/03
1K0
Redis---整合SpringBoot篇
Redis6 1、引入redis相关依赖 2、application.properties配置redis配置 3.添加redis配置类 4.测试一下 RedisTemplate基本使用如下 ---- 1、引入redis相关依赖 <!-- redis的启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </depende
大忽悠爱学习
2021/11/15
2940
Springboot中的redis配置类
简单记录一下 首先依赖: <!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- spring2.X集成redis所需common-pool2-->
Tom2Code
2022/11/21
6790
SpringBoot整合redis
前言 使用注解实现Redis缓存功能的具体代码 1 引入jar包 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 2 添加配置 spring.redis.host=xxxxxxx spring.redis.port=6379 // 如
在水一方
2022/10/04
3000
springboot整合redis进行缓存的使用
看过我的文章的都应该有所了解如何使用docker方式进行redis环境的搭建过程,想要了解的可以看下历史文章。今天我们想要分享的就是如何使用redis进行缓存的使用。
码农王同学
2019/11/28
5050
springboot整合redis进行缓存的使用
SpringBoot 整合 Redis
因为 Redis 有 这5种基本数据结构类型分别为:String(字符串)、List(列表)、Set(集合)、Hash(散列)和 Zset(有序集合)。
收心
2022/01/17
3760
SpringBoot 整合 Redis
redis过期监听
今天写拼团功能,如果24小时后还没有人满,则此次拼团就失败了,那么这里我用redis过期监听来实现,键过期去处理订单状态等业务
adu
2022/10/30
2.3K0
redis过期监听
Spring Boot 结合 Redis 的序列化配置
默认情况下,Spring 为我们提供了一个 RedisTemplate 来进行对 Redis 的操作,但是 RedisTemplate 默认配置的是使用Java本机序列化。
Vincent-yuan
2021/10/28
4.1K0
Spring Boot 结合 Redis 的序列化配置
springboot2.0+redis 二级缓存 乱码问题
SpringCacheRedisConfig import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.
用户5899361
2020/12/07
4891
SpringBoot集成Redis缓存
https://www.cnblogs.com/noneplus/p/11532065.html
Noneplus
2019/09/24
5960
SpringBoot集成Redis缓存
从零搭建Spring Boot脚手架(6):整合Redis作为缓存
上一文我们整合了Mybatis Plus,今天我们会把缓存也集成进来。缓存是一个系统应用必备的一种功能,除了在减轻数据库的压力之外。还在存储一些短时效的数据场景中发挥着重大作用,比如存储用户Token、短信验证码等等,目前缓存的选型还是比较多的,EHCACHE、HAZELCAST、CAFFEINE、COUCHBASE以及本文要整合的REDIS。接下来我们将会在kono脚手架项目中集成Spring Cache以及Redis。
码农小胖哥
2020/08/25
9760
从零搭建Spring Boot脚手架(6):整合Redis作为缓存
spring boot redis 缓存_redis本地缓存
查询操作是应用中最常见的操作,如果每次查询都从 MySQL 中查询则会影响效率,通常需要引入缓存来实现查询性能的优化。缓存可以选择本地缓存,远程缓存或本地缓存结合远程缓存。本地缓存可以使用 Guava 或 Caffeine 提供的解决方案,而远程缓存则可以选择 Redis 这样的内存数据库。本文记录一下 SpringBoot 集成 Redis 做缓存的相关配置。
全栈程序员站长
2022/09/30
2.1K0
springboot配置RedisTemplate和RedisCacheManager
1、项目目录结构: 2、application.properties配置文件: 我这里redis连的是虚拟机上面的,你改下host地址就行 spring.datasource.url=jdbc:mysql://localhost:3306/spring_cache spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jd
别团等shy哥发育
2023/02/25
1.2K0
springboot配置RedisTemplate和RedisCacheManager
SpringBoot集成Redis引起的序列化问题
想必大家对SpringBoot可能已经很熟悉了,包括集成Redis这种常用的技术,之前一直用一贯的写法去集成Redis,写配置类没发现过任何问题,但是上周在给Redis配置类加了一个Bean之后就出现了很难发现的问题。
一个程序员的成长
2020/11/25
1.5K0
2 Springboot中使用redis,配置redis的key value生成策略
上一篇里讲过了redis在spring boot中的简单使用,对于单个对象的增删改查的默认操作。
天涯泪小武
2019/01/17
4K2
springboot高级特性-redis作为缓存
springboot版本为2.5.4 redis版本 3.2 引入starter
暴躁的程序猿
2022/03/23
4100
springboot高级特性-redis作为缓存
Spring Boot---(6)SpringBoot整合Redis
1.引入依赖 <!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>1.5.6.RELEASE</version> </dependency> 2.配置文件 # redis # Redis数据库索引(默认为0) spring.redis.databas
IT云清
2019/01/22
5010
spring-boot-2.0.3之redis缓存实现,不是你想的那样哦!
    小白问小明:“你前面有一个5米深的坑,里面没有水,如果你跳进去后该怎样出来了?”小明:“躺着出来呗,还能怎么出来?”小白:“为什么躺着出来?”小明:“5米深的坑,还没有水,跳下去不死就很幸运了,残是肯定会残的,不躺着出来,那能怎么出来?”小白:“假设没死也没残呢?”小明:“你当我超人了? 那也简单,把脑子里的水放出来就可以漂出来了。”小白:“你脑子里有这么多水吗?”小明:“我脑子里没那么多水我跳下去干嘛?” 
青石路
2018/12/06
2.5K0
spring-boot-2.0.3之redis缓存实现,不是你想的那样哦!
springboot缓存之自定义CacheManager
先要说明的是上一节springboot缓存之使用redis作为缓存管理是springboot的旧版本了,最新的springboot2.x已经不这么用了,而且缓存注解一般用于service上,而不是controller上。百度了下整体代码是这样的:MyRedisConfig.java
西西嘛呦
2020/08/26
3.5K0
SpringBoot中Redis的基础使用
然后在根包下创建一个service的文件夹加,然后在里面增加redis文件夹,redis文件夹里编写redis的基础操作函数。
Kiba518
2023/07/09
3290
SpringBoot中Redis的基础使用
相关推荐
Spring Boot 整合 Redis
更多 >
领券
社区富文本编辑器全新改版!诚邀体验~
全新交互,全新视觉,新增快捷键、悬浮工具栏、高亮块等功能并同时优化现有功能,全面提升创作效率和体验
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文