【mall-learning】03-mall整合Redis实现缓存功能

2024-04-20 15:08

本文主要是介绍【mall-learning】03-mall整合Redis实现缓存功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Redis的安装和启动

Redis是用C语言开发的一个高性能键值对数据库,可用于数据缓存,主要用于处理大量数据的高访问负载。

  • 下载Redis,下载地址:https://github.com/MicrosoftArchive/redis/releases

展示图片

 

  • 下载完后解压到指定目录

展示图片

 

  • 在当前地址栏输入cmd后,执行redis的启动命令:redis-server.exe redis.windows.conf

展示图片

 

整合Redis

添加项目依赖

在pom.xml中新增Redis相关依赖

<!--redis依赖配置-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

 

修改SpringBoot配置文件

在application.yml中添加Redis的配置及Redis中自定义key的配置。

在spring节点下添加Redis的配置

  redis:host: localhost # Redis服务器地址database: 0 # Redis数据库索引(默认为0)port: 6379 # Redis服务器连接端口password: # Redis服务器连接密码(默认为空)jedis:pool:max-active: 8 # 连接池最大连接数(使用负值表示没有限制)max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制)max-idle: 8 # 连接池中的最大空闲连接min-idle: 0 # 连接池中的最小空闲连接timeout: 3000ms # 连接超时时间(毫秒)

 在根节点下添加Redis自定义key的配置

# 自定义redis key
redis:key:prefix:authCode: "portal:authCode:"expire:authCode: 120 # 验证码超期时间

 添加RedisService接口用于定义一些常用Redis操作

package com.macro.mall.tiny.service;/*** redis操作Service,* 对象和数组都以json形式进行存储* Created by macro on 2018/8/7.*/
public interface RedisService {/*** 存储数据*/void set(String key, String value);/*** 获取数据*/String get(String key);/*** 设置超期时间*/boolean expire(String key, long expire);/*** 删除数据*/void remove(String key);/*** 自增操作* @param delta 自增步长*/Long increment(String key, long delta);}

注入StringRedisTemplate,实现RedisService接口

package com.macro.mall.tiny.service.impl;import com.macro.mall.tiny.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;import java.util.concurrent.TimeUnit;/*** redis操作Service的实现类* Created by macro on 2018/8/7.*/
@Service
public class RedisServiceImpl implements RedisService {@Autowiredprivate StringRedisTemplate stringRedisTemplate;@Overridepublic void set(String key, String value) {stringRedisTemplate.opsForValue().set(key, value);}@Overridepublic String get(String key) {return stringRedisTemplate.opsForValue().get(key);}@Overridepublic boolean expire(String key, long expire) {return stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);}@Overridepublic void remove(String key) {stringRedisTemplate.delete(key);}@Overridepublic Long increment(String key, long delta) {return stringRedisTemplate.opsForValue().increment(key,delta);}
}

添加UmsMemberController

添加根据电话号码获取验证码的接口和校验验证码的接口

package com.macro.mall.tiny.controller;import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.service.UmsMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;/*** 会员登录注册管理Controller* Created by macro on 2018/8/3.*/
@Controller
@Api(tags = "UmsMemberController", description = "会员登录注册管理")
@RequestMapping("/sso")
public class UmsMemberController {@Autowiredprivate UmsMemberService memberService;@ApiOperation("获取验证码")@RequestMapping(value = "/getAuthCode", method = RequestMethod.GET)@ResponseBodypublic CommonResult getAuthCode(@RequestParam String telephone) {return memberService.generateAuthCode(telephone);}@ApiOperation("判断验证码是否正确")@RequestMapping(value = "/verifyAuthCode", method = RequestMethod.POST)@ResponseBodypublic CommonResult updatePassword(@RequestParam String telephone,@RequestParam String authCode) {return memberService.verifyAuthCode(telephone,authCode);}
}

 添加UmsMemberService接口

package com.macro.mall.tiny.service;import com.macro.mall.tiny.common.api.CommonResult;/*** 会员管理Service* Created by macro on 2018/8/3.*/
public interface UmsMemberService {/*** 生成验证码*/CommonResult generateAuthCode(String telephone);/*** 判断验证码和手机号码是否匹配*/CommonResult verifyAuthCode(String telephone, String authCode);}

添加UmsMemberService接口的实现类UmsMemberServiceImpl

生成验证码时,将自定义的Redis键值加上手机号生成一个Redis的key,以验证码为value存入到Redis中,并设置过期时间为自己配置的时间(这里为120s)。校验验证码时根据手机号码来获取Redis里面存储的验证码,并与传入的验证码进行比对。

 

package com.macro.mall.tiny.service.impl;import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.service.RedisService;
import com.macro.mall.tiny.service.UmsMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;import java.util.Random;/*** 会员管理Service实现类* Created by macro on 2018/8/3.*/
@Service
public class UmsMemberServiceImpl implements UmsMemberService {@Autowiredprivate RedisService redisService;@Value("${redis.key.prefix.authCode}")private String REDIS_KEY_PREFIX_AUTH_CODE;@Value("${redis.key.expire.authCode}")private Long AUTH_CODE_EXPIRE_SECONDS;@Overridepublic CommonResult generateAuthCode(String telephone) {StringBuilder sb = new StringBuilder();Random random = new Random();for (int i = 0; i < 6; i++) {sb.append(random.nextInt(10));}//验证码绑定手机号并存储到redisredisService.set(REDIS_KEY_PREFIX_AUTH_CODE + telephone, sb.toString());redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE + telephone, AUTH_CODE_EXPIRE_SECONDS);return CommonResult.success(sb.toString(), "获取验证码成功");}//对输入的验证码进行校验@Overridepublic CommonResult verifyAuthCode(String telephone, String authCode) {if (StringUtils.isEmpty(authCode)) {return CommonResult.failed("请输入验证码");}String realAuthCode = redisService.get(REDIS_KEY_PREFIX_AUTH_CODE + telephone);boolean result = authCode.equals(realAuthCode);if (result) {return CommonResult.success(null, "验证码校验成功");} else {return CommonResult.failed("验证码不正确");}}}

运行项目

访问Swagger的API文档地址http://localhost:8080/swagger-ui.html ,对接口进行测试。

 

展示图片

 

这篇关于【mall-learning】03-mall整合Redis实现缓存功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/920583

相关文章

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

缓存雪崩问题

缓存雪崩是缓存中大量key失效后当高并发到来时导致大量请求到数据库,瞬间耗尽数据库资源,导致数据库无法使用。 解决方案: 1、使用锁进行控制 2、对同一类型信息的key设置不同的过期时间 3、缓存预热 1. 什么是缓存雪崩 缓存雪崩是指在短时间内,大量缓存数据同时失效,导致所有请求直接涌向数据库,瞬间增加数据库的负载压力,可能导致数据库性能下降甚至崩溃。这种情况往往发生在缓存中大量 k

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略 1. 特权模式限制2. 宿主机资源隔离3. 用户和组管理4. 权限提升控制5. SELinux配置 💖The Begin💖点点关注,收藏不迷路💖 Kubernetes的PodSecurityPolicy(PSP)是一个关键的安全特性,它在Pod创建之前实施安全策略,确保P