当前位置:首页 > 文章列表 > 数据库 > Redis > 使用SpringBoot集成redis的方法

使用SpringBoot集成redis的方法

来源:脚本之家 2022-12-30 07:57:57 0浏览 收藏

在数据库实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《使用SpringBoot集成redis的方法》,聊聊Redis、SpringBoot集成,希望可以帮助到正在努力赚钱的你。

今天,日月在这里教大家如何使用springBoot集成redis,说实话比较简单,网上也有大把的教程。先套用一下网上的简介。
定义

REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统。
Redis是一个开源的使用ANSI C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。
它通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型。
reids的优点

以下是Redis的一些优点。

异常快 - Redis非常快,每秒可执行大约110000次的设置(SET)操作,每秒大约可执行81000次的读取/获取(GET)操作。
支持丰富的数据类型 - Redis支持开发人员常用的大多数数据类型,例如列表,集合,排序集和散列等等。这使得Redis很容易被用来解决各种问题,因为我们知道哪些问题可以更好使用地哪些数据类型来处理解决。
操作具有原子性 - 所有Redis操作都是原子操作,这确保如果两个客户端并发访问,Redis服务器能接收更新的值。
多实用工具 - Redis是一个多实用工具,可用于多种用例,如:缓存,消息队列(Redis本地支持发布/订阅),应用程序中的任何短期数据,例如,web应用程序中的会话,网页命中计数等。

Redis 安装

Window 下安装
下载地址:https://github.com/MSOpenTech/redis/releases。
Redis 支持 32 位和 64 位。这个需要根据你系统平台的实际情况选择,这里我们下载 Redis-x64-xxx.zip压缩包到 C 盘,解压后,将文件夹重新命名为 redis。

打开一个 cmd 窗口 使用cd命令切换目录到 C:\redis
运行 redis-server.exe redis.windows.conf
如果想方便的话,可以把 redis 的路径加到系统的环境变量里,这样就省得再输路径了,后面的那个 redis.windows.conf 可以省略,如果省略,会启用默认的。输入之后,会显示如下界面:

在这里插入图片描述

集成redis

我们还是延用上一章的项目:Springboot集成springcloud-config实现dataSource热部署

1、添加依赖


org.springframework.bootspring-boot-starter-redis1.4.1.RELEASEcom.alibabafastjson1.2.3com.fasterxml.jackson.corejackson-databind

2、在配置中心里添加redis配置

spring.redis.host=127.0.0.1
#Redis服务器连接端口
spring.redis.port=6379
#Redis服务器连接密码(默认为空)
spring.redis.password=
#连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
#连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
#连接池中的最大空闲连接
spring.redis.pool.max-idle=8
#连接池中的最小空闲连接
spring.redis.pool.min-idle=0
#连接超时时间(毫秒)
spring.redis.timeout=30000

3、配置类RedisConfig

import java.lang.reflect.Method;
import org.springframework.beans.factory.annotation.Value;
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.cloud.context.config.annotation.RefreshScope;
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.connection.jedis.JedisConnectionFactory;
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.PropertyAccessor; 
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@EnableCaching
@RefreshScope
public class RedisConfig extends CachingConfigurerSupport{
 @Value("${spring.redis.host}")
 private String host;
 @Value("${spring.redis.port}")
 private int port;
 @Value("${spring.redis.timeout}")
 private int timeout;
 @Value("${spring.redis.password}")
 private String password;
 @Value("${spring.redis.pool.max-active}")
 private int maxActive;
 @Value("${spring.redis.pool.max-wait}")
 private int maxWait;
 @Value("${spring.redis.pool.max-idle}")
 private int maxIdle;
 @Value("${spring.redis.pool.min-idle}")
 private int minIdle;
 
 @RefreshScope
 @Bean
 public KeyGenerator wiselyKeyGenerator(){
 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();
 }
 };
 }
 
 @RefreshScope
 @Bean
 public JedisConnectionFactory redisConnectionFactory() {
 JedisConnectionFactory factory = new JedisConnectionFactory();
 factory.setHostName(host);
 factory.setPort(port);
 factory.setTimeout(timeout); //设置连接超时时间
 factory.setPassword(password);
 factory.getPoolConfig().setMaxIdle(maxIdle);
 factory.getPoolConfig().setMinIdle(minIdle);
 factory.getPoolConfig().setMaxTotal(maxActive);
 factory.getPoolConfig().setMaxWaitMillis(maxWait);
 return factory;
 }
 
 @RefreshScope
 @Bean
 public CacheManager cacheManager(RedisTemplate redisTemplate) {
 RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
 // Number of seconds before expiration. Defaults to unlimited (0)
 cacheManager.setDefaultExpiration(10); //设置key-value超时时间
 return cacheManager;
 }
 
 @RefreshScope
 @Bean
 public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
 StringRedisTemplate template = new StringRedisTemplate(factory);
 setSerializer(template); //设置序列化工具,这样ReportBean不需要实现Serializable接口
 template.afterPropertiesSet();
 return template;
 }
 
 @RefreshScope
 private void setSerializer(StringRedisTemplate template) {
 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);
 }
}

4、RedisUtils类

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
@Service
public class RedisUtils {
 @Autowired
 private RedisTemplate redisTemplate;
 /**
 * 写入缓存
 * @param key
 * @param value
 * @return
 */
 public boolean set(final String key, Object value) {
 boolean result = false;
 try {
 ValueOperations operations = redisTemplate.opsForValue();
 operations.set(key, value);
 result = true;
 } catch (Exception e) {
 e.printStackTrace();
 }
 return result;
 }
 /**
 * 写入缓存设置时效时间
 * @param key
 * @param value
 * @return
 */
 public boolean set(final String key, Object value, Long expireTime ,TimeUnit timeUnit) {
 boolean result = false;
 try {
 ValueOperations operations = redisTemplate.opsForValue();
 operations.set(key, value);
 redisTemplate.expire(key, expireTime, timeUnit);
 result = true;
 } catch (Exception e) {
 e.printStackTrace();
 }
 return result;
 }
 /**
 * 批量删除对应的value
 * @param keys
 */
 public void remove(final String... keys) {
 for (String key : keys) {
 remove(key);
 }
 }
 /**
 * 批量删除key
 * @param pattern
 */
 public void removePattern(final String pattern) {
 Set keys = redisTemplate.keys(pattern);
 if (keys.size() > 0){
 redisTemplate.delete(keys);
 }
 }
 /**
 * 删除对应的value
 * @param key
 */
 public void remove(final String key) {
 if (exists(key)) {
 redisTemplate.delete(key);
 }
 }
 /**
 * 判断缓存中是否有对应的value
 * @param key
 * @return
 */
 public boolean exists(final String key) {
 return redisTemplate.hasKey(key);
 }
 /**
 * 读取缓存
 * @param key
 * @return
 */
 public Object get(final String key) {
 Object result = null;
 ValueOperations operations = redisTemplate.opsForValue();
 result = operations.get(key);
 return result;
 }
 /**
 * 哈希 添加
 * @param key
 * @param hashKey
 * @param value
 */
 public void hmSet(String key, Object hashKey, Object value){
 HashOperations hash = redisTemplate.opsForHash();
 hash.put(key,hashKey,value);
 }
 /**
 * 哈希获取数据
 * @param key
 * @param hashKey
 * @return
 */
 public Object hmGet(String key, Object hashKey){
 HashOperations hash = redisTemplate.opsForHash();
 return hash.get(key,hashKey);
 }
 /**
 * 列表添加
 * @param k
 * @param v
 */
 public void lPush(String k,Object v){
 ListOperations list = redisTemplate.opsForList();
 list.rightPush(k,v);
 }
 /**
 * 列表获取
 * @param k
 * @param l
 * @param l1
 * @return
 */
 public List lRange(String k, long l, long l1){
 ListOperations list = redisTemplate.opsForList();
 return list.range(k,l,l1);
 }
 /**
 * 集合添加
 * @param key
 * @param value
 */
 public void add(String key,Object value){
 SetOperations set = redisTemplate.opsForSet();
 set.add(key,value);
 }
 /**
 * 集合获取
 * @param key
 * @return
 */
 public Set setMembers(String key){
 SetOperations set = redisTemplate.opsForSet();
 return set.members(key);
 }
 /**
 * 有序集合添加
 * @param key
 * @param value
 * @param scoure
 */
 public void zAdd(String key,Object value,double scoure){
 ZSetOperations zset = redisTemplate.opsForZSet();
 zset.add(key,value,scoure);
 }
 /**
 * 有序集合获取
 * @param key
 * @param scoure
 * @param scoure1
 * @return
 */
 public Set rangeByScore(String key,double scoure,double scoure1){
 ZSetOperations zset = redisTemplate.opsForZSet();
 return zset.rangeByScore(key, scoure, scoure1);
 }

5、测试,修改controller

import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RestController;
import com.chenqi.springboot.redis.RedisUtils;
import com.chenqi.springboot.service.TestService;
@RestController
public class SpringBootController {
 
 public static final Logger log = LoggerFactory.getLogger(SpringBootController.class);
 
 @Autowired
 TestService testService;
 
 @Autowired
 private RedisUtils redisUtils;
 @RequestMapping(value = "/hello/{id}")
 public String hello(@PathVariable(value = "id") String id){
 //查询缓存中是否存在
 boolean hasKey = redisUtils.exists(id);
 String str = "";
 if(hasKey){
 //获取缓存
 Object object = redisUtils.get(id);
 log.info("从缓存获取的数据"+ object);
 str = object.toString();
 }else{
 //从数据库中获取信息
 log.info("从数据库中获取数据");
 str = testService.test();
 //数据插入缓存(set中的参数含义:key值,user对象,缓存存在时间10(long类型),时间单位)
 redisUtils.set(id,str,10L,TimeUnit.MINUTES);
 log.info("数据插入缓存" + str);
 }
 return str;
 }
}

启动项目,第一次访问:http://localhost:8002/hello/111

在这里插入图片描述
在这里插入图片描述

通过控制台输出,我们可以看到是从数据库中获取的数据,并且存入了redis缓存中。

我们再次刷新浏览器

在这里插入图片描述

可以看到,第二次是从缓存中读取的,我们试试不断刷新浏览器

在这里插入图片描述

可以看到,之后都是从缓存中获取的。

到此我们的redis就配置好了。

SpringBoot集成Redis-demo下载

急需demo的兄弟就自行下载吧,不急可以留言邮箱,一般48小时内会发。

理论要掌握,实操不能落!以上关于《使用SpringBoot集成redis的方法》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

版本声明
本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
如何自定义redis工具jar包供其他SpringBoot项目直接使用如何自定义redis工具jar包供其他SpringBoot项目直接使用
上一篇
如何自定义redis工具jar包供其他SpringBoot项目直接使用
Redis解决库存超卖问题实例讲解
下一篇
Redis解决库存超卖问题实例讲解
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    543次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    516次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    500次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    485次学习
查看更多
AI推荐
  • ChatExcel酷表:告别Excel难题,北大团队AI助手助您轻松处理数据
    ChatExcel酷表
    ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
    6073次使用
  • Any绘本:开源免费AI绘本创作工具深度解析
    Any绘本
    探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
    6492次使用
  • 可赞AI:AI驱动办公可视化智能工具,一键高效生成文档图表脑图
    可赞AI
    可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
    6302次使用
  • 星月写作:AI网文创作神器,助力爆款小说速成
    星月写作
    星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
    8265次使用
  • MagicLight.ai:叙事驱动AI动画视频创作平台 | 高效生成专业级故事动画
    MagicLight
    MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
    6899次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码