和get redis_SpringBoot整合Redis,你get了吗?

Our-task介绍

本篇博客是我github上our-task:一个完整的清单管理系统的配套教程文档,这是SpringBoot+Vue开发的前后端分离清单管理工具,仿滴答清单。目前已部署在阿里云ECS上,可进行在线预览,随意使用(附详细教程),大家感兴趣的话,欢迎给个star!

阿里云预览地址

Redis的安装与配置

Windows下redis的安装与配置

SpringBoot整合Redis

添加项目依赖

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

yml文件配置

yml文件中主要是关于Redis的配置,其中键的设置格式为:数据库名:表名:id,更多Redis了解,请大家参考这篇文章。

Redis各种键的典型使用场景,不清楚的都来看一下

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

实体类

新建entity包,在该包下新建User类,用作该Demo的操作实体。考虑到一些小白可能还不了解Lombok,我就直接使用Setter/Getter。

package com.example.demo.entity;
​
/*** @program: SpringBoot-Redis-Demo* @description: 用户类* @author: water76016* @create: 2020-12-29 09:22**/
public class User {Integer id;String username;String password;
​public User(Integer id, String username, String password) {this.id = id;this.username = username;this.password = password;}
​@Overridepublic String toString() {return "User{" +"username='" + username + ''' +", password='" + password + ''' +'}';}
​public Integer getId() {return id;}
​public void setId(Integer id) {this.id = id;}
​public String getUsername() {return username;}
​public void setUsername(String username) {this.username = username;}
​public String getPassword() {return password;}
​public void setPassword(String password) {this.password = password;}
}

Service服务接口

服务接口一共有两个:一个是UserService,一个是RedisService。UserService提供了针对User实体的服务,RedisService提供操作Reids的服务接口。

package com.example.demo.service;
​
import com.example.demo.entity.User;
​
public interface UserService {/*** 对用户打招呼,返回user的toString()方法* @param user* @return*/public String helloUser(User user);
}
package com.example.demo.service;
​
import java.util.List;
import java.util.Map;
import java.util.Set;
​
​
/*** @program: our-task* @description: redis操作服务类* @author: water76016* @create: 2020-09-24 16:45**/
public interface RedisService {
​/*** 保存属性** @param key   the key* @param value the value* @param time  the time*/void set(String key, Object value, long time);
​/*** 保存属性** @param key   键* @param value 值*/void set(String key, Object value);
​/*** 获取属性** @param key the key* @return the object*/Object get(String key);
​/*** 删除属性** @param key the key* @return the boolean*/Boolean del(String key);
​/*** 批量删除属性** @param keys the keys* @return the long*/Long del(List<String> keys);
​/*** 设置过期时间** @param key  the key* @param time the time* @return the boolean*/Boolean expire(String key, long time);
​/*** 获取过期时间** @param key the key* @return the expire*/Long getExpire(String key);
​/*** 判断是否有该属性** @param key the key* @return the boolean*/Boolean hasKey(String key);
​/*** 按delta递增** @param key   the key* @param delta the delta* @return the long*/Long incr(String key, long delta);
​/*** 按delta递减** @param key   the key* @param delta the delta* @return the long*/Long decr(String key, long delta);
​/*** 获取Hash结构中的属性** @param key     the key* @param hashKey the hash key* @return the object*/Object hGet(String key, String hashKey);
​/*** 向Hash结构中放入一个属性** @param key     the key* @param hashKey the hash key* @param value   the value* @param time    the time* @return the boolean*/Boolean hSet(String key, String hashKey, Object value, long time);
​/*** 向Hash结构中放入一个属性** @param key     the key* @param hashKey the hash key* @param value   the value*/void hSet(String key, String hashKey, Object value);
​/*** 直接获取整个Hash结构** @param key the key* @return the map*/Map<Object, Object> hGetAll(String key);
​/*** 直接设置整个Hash结构** @param key  the key* @param map  the map* @param time the time* @return the boolean*/Boolean hSetAll(String key, Map<String, Object> map, long time);
​/*** 直接设置整个Hash结构** @param key the key* @param map the map*/void hSetAll(String key, Map<String, Object> map);
​/*** 删除Hash结构中的属性** @param key     the key* @param hashKey the hash key*/void hDel(String key, Object... hashKey);
​/*** 判断Hash结构中是否有该属性** @param key     the key* @param hashKey the hash key* @return the boolean*/Boolean hHasKey(String key, String hashKey);
​/*** Hash结构中属性递增** @param key     the key* @param hashKey the hash key* @param delta   the delta* @return the long*/Long hIncr(String key, String hashKey, Long delta);
​/*** Hash结构中属性递减** @param key     the key* @param hashKey the hash key* @param delta   the delta* @return the long*/Long hDecr(String key, String hashKey, Long delta);
​/*** 获取Set结构** @param key the key* @return the set*/Set<Object> sMembers(String key);
​/*** 向Set结构中添加属性** @param key    the key* @param values the values* @return the long*/Long sAdd(String key, Object... values);
​/*** 向Set结构中添加属性** @param key    the key* @param time   the time* @param values the values* @return the long*/Long sAdd(String key, long time, Object... values);
​/*** 是否为Set中的属性** @param key   the key* @param value the value* @return the boolean*/Boolean sIsMember(String key, Object value);
​/*** 获取Set结构的长度** @param key the key* @return the long*/Long sSize(String key);
​/*** 删除Set结构中的属性** @param key    the key* @param values the values* @return the long*/Long sRemove(String key, Object... values);
​/*** 获取List结构中的属性** @param key   the key* @param start the start* @param end   the end* @return the list*/List<Object> lRange(String key, long start, long end);
​/*** 获取List结构的长度** @param key the key* @return the long*/Long lSize(String key);
​/*** 根据索引获取List中的属性** @param key   the key* @param index the index* @return the object*/Object lIndex(String key, long index);
​/*** 向List结构中添加属性** @param key   the key* @param value the value* @return the long*/Long lPush(String key, Object value);
​/*** 向List结构中添加属性** @param key   the key* @param value the value* @param time  the time* @return the long*/Long lPush(String key, Object value, long time);
​/*** 向List结构中批量添加属性** @param key    the key* @param values the values* @return the long*/Long lPushAll(String key, Object... values);
​/*** 向List结构中批量添加属性** @param key    the key* @param time   the time* @param values the values* @return the long*/Long lPushAll(String key, Long time, Object... values);
​/*** 从List结构中移除属性** @param key   the key* @param count the count* @param value the value* @return the long*/Long lRemove(String key, long count, Object value);
}

Service实现类

在UserService中,我们把用户的信息存储在Redis中。调用了RedisService的方法,同时给该键设置过期时间。大家在操作的时候,直接使用RedisService中的方法就可以了,这些方法还是挺全的。

package com.example.demo.service.impl;
​
import com.example.demo.entity.User;
import com.example.demo.service.RedisService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
​
/*** @program: SpringBoot-Redis-Demo* @description: 用户服务实现类* @author: water76016* @create: 2020-12-29 09:24**/
@Service
public class UserServiceImpl implements UserService {@AutowiredRedisService redisService;
​@Value("${redis.database}")private String redisDatabase;@Value("${redis.key.user}")private String redisUserKey;@Value("${redis.expire.common}")private long expire;/*** 对用户打招呼,返回user的toString()方法** @param user* @return*/@Overridepublic String helloUser(User user) {//设置键,键的格式为:数据库名:user:用户idString key = redisDatabase + ":" + redisUserKey + ":" + user.getId();//把用户的toString,存在这个键里面redisService.set(key, user.toString());//设置键的过期时间redisService.expire(key, expire);return user.toString();}
}
package com.example.demo.service.impl;
​
import com.example.demo.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
​
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
​
/*** @program: our-task* @description: redis操作服务接口实现类* @author: water76016* @create: 2020-09-24 16:45**/
@Service
public class RedisServiceImpl implements RedisService {/*** 由于没有指定具体类型<String, Object>,用Resource注入才有效* */@Resourceprivate RedisTemplate redisTemplate;
​@Autowired(required = false)public void setRedisTemplate(RedisTemplate redisTemplate) {RedisSerializer stringSerializer = new StringRedisSerializer();redisTemplate.setKeySerializer(stringSerializer);redisTemplate.setValueSerializer(stringSerializer);redisTemplate.setHashKeySerializer(stringSerializer);redisTemplate.setHashValueSerializer(stringSerializer);this.redisTemplate = redisTemplate;}@Overridepublic void set(String key, Object value, long time) {redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);}
​@Overridepublic void set(String key, Object value) {
​redisTemplate.opsForValue().set(key, value);}
​@Overridepublic Object get(String key) {return redisTemplate.opsForValue().get(key);}
​@Overridepublic Boolean del(String key) {return redisTemplate.delete(key);}
​@Overridepublic Long del(List<String> keys) {return redisTemplate.delete(keys);}
​@Overridepublic Boolean expire(String key, long time) {return redisTemplate.expire(key, time, TimeUnit.SECONDS);}
​@Overridepublic Long getExpire(String key) {return redisTemplate.getExpire(key, TimeUnit.SECONDS);}
​@Overridepublic Boolean hasKey(String key) {return redisTemplate.hasKey(key);}
​@Overridepublic Long incr(String key, long delta) {return redisTemplate.opsForValue().increment(key, delta);}
​@Overridepublic Long decr(String key, long delta) {return redisTemplate.opsForValue().increment(key, -delta);}
​@Overridepublic Object hGet(String key, String hashKey) {return redisTemplate.opsForHash().get(key, hashKey);}
​@Overridepublic Boolean hSet(String key, String hashKey, Object value, long time) {redisTemplate.opsForHash().put(key, hashKey, value);return expire(key, time);}
​@Overridepublic void hSet(String key, String hashKey, Object value) {redisTemplate.opsForHash().put(key, hashKey, value);}
​@Overridepublic Map<Object, Object> hGetAll(String key) {return redisTemplate.opsForHash().entries(key);}
​@Overridepublic Boolean hSetAll(String key, Map<String, Object> map, long time) {redisTemplate.opsForHash().putAll(key, map);return expire(key, time);}
​@Overridepublic void hSetAll(String key, Map<String, Object> map) {redisTemplate.opsForHash().putAll(key, map);}
​@Overridepublic void hDel(String key, Object... hashKey) {redisTemplate.opsForHash().delete(key, hashKey);}
​@Overridepublic Boolean hHasKey(String key, String hashKey) {return redisTemplate.opsForHash().hasKey(key, hashKey);}
​@Overridepublic Long hIncr(String key, String hashKey, Long delta) {return redisTemplate.opsForHash().increment(key, hashKey, delta);}
​@Overridepublic Long hDecr(String key, String hashKey, Long delta) {return redisTemplate.opsForHash().increment(key, hashKey, -delta);}
​@Overridepublic Set<Object> sMembers(String key) {return redisTemplate.opsForSet().members(key);}
​@Overridepublic Long sAdd(String key, Object... values) {return redisTemplate.opsForSet().add(key, values);}
​@Overridepublic Long sAdd(String key, long time, Object... values) {Long count = redisTemplate.opsForSet().add(key, values);expire(key, time);return count;}
​@Overridepublic Boolean sIsMember(String key, Object value) {return redisTemplate.opsForSet().isMember(key, value);}
​@Overridepublic Long sSize(String key) {return redisTemplate.opsForSet().size(key);}
​@Overridepublic Long sRemove(String key, Object... values) {return redisTemplate.opsForSet().remove(key, values);}
​@Overridepublic List<Object> lRange(String key, long start, long end) {return redisTemplate.opsForList().range(key, start, end);}
​@Overridepublic Long lSize(String key) {return redisTemplate.opsForList().size(key);}
​@Overridepublic Object lIndex(String key, long index) {return redisTemplate.opsForList().index(key, index);}
​@Overridepublic Long lPush(String key, Object value) {return redisTemplate.opsForList().rightPush(key, value);}
​@Overridepublic Long lPush(String key, Object value, long time) {Long index = redisTemplate.opsForList().rightPush(key, value);expire(key, time);return index;}
​@Overridepublic Long lPushAll(String key, Object... values) {return redisTemplate.opsForList().rightPushAll(key, values);}
​@Overridepublic Long lPushAll(String key, Long time, Object... values) {Long count = redisTemplate.opsForList().rightPushAll(key, values);expire(key, time);return count;}
​@Overridepublic Long lRemove(String key, long count, Object value) {return redisTemplate.opsForList().remove(key, count, value);}
}

UserController控制器

接下来,我们新建一个controller包,在该包下新建UserController控制类。

package com.example.demo.controller;
​
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
​
/*** @program: SpringBoot-Redis-Demo* @description:* @author: water76016* @create: 2020-12-29 09:27**/
@RestController
@RequestMapping("/user")
public class UserController {@AutowiredUserService userService;
​@PostMapping("/helloUser")public String helloUser(@RequestBody User user){return userService.helloUser(user);}
​
}

结果测试

最后,我们启动SpringBoot程序,程序运行在8080端口,在postman中进行测试。大家按照我在postman中的输入,就会有相应的输出了。

c3e6f8de8047a06e2ab765244dc3d7fd.png

另外,也来看看Redis中是否有相应的缓存结果。

26b6d1fd3b88867fa0813423528bd3e8.png

Demo地址

写了这么多,还是担心大家使用的时候有问题,所以我把该Demo放在了Github上,大家自行下载就可以了。

SpringBoot-Redis-Demo地址

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/393734.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

linux课程设计qq,仿QQ聊天系统课程设计.doc

目录绪论1一&#xff0e;需求分析11.1软件功能需求分析21.2 安全需求分析2二&#xff0e;总体设计32.1 软件结构图32.2 功能描述32.2.1注册功能概要42.2.2登录功能概要42.2.3聊天功能概要52.3 安全设计6三&#xff0e;数据库设计63.1概念结构设计63.2逻辑结构设计73.3物理结构设…

ocp linux 基础要点

基本命令&#xff1a; 创建/修改/删除用户 useradd/usermod/userdel 创建/修改/删除用户组 groupadd/groupmod/groupdel 修改所属用户/所属用户组 chown/chgrp 修改权限 chmod 创建文件夹 mkdir 创建文件 touch 切换目录 …

leetcode1386. 安排电影院座位(贪心)

如上图所示&#xff0c;电影院的观影厅中有 n 行座位&#xff0c;行编号从 1 到 n &#xff0c;且每一行内总共有 10 个座位&#xff0c;列编号从 1 到 10 。 给你数组 reservedSeats &#xff0c;包含所有已经被预约了的座位。比如说&#xff0c;researvedSeats[i][3,8] &…

首席技术执行官_如何在几分钟内找到任何首席执行官的电子邮件地址

首席技术执行官by Theo Strauss由西奥斯特劳斯(Theo Strauss) 如何在几分钟内找到任何首席执行官的电子邮件地址 (How to find any CEO’s email address in minutes) 银河电子邮件指南&#xff1a;第一部分 (The Emailer’s Guide To The Galaxy: Part I) I’m 17, so my net…

Linux 查看磁盘或文件夹及文件大小

当磁盘大小超过标准时会有报警提示&#xff0c;这时如果掌握df和du命令是非常明智的选择。 df可以查看一级文件夹大小、使用比例、档案系统及其挂入点&#xff0c;但对文件却无能为力。 du可以查看文件及文件夹的大小。 两者配合使用&#xff0c;非常有效。比如用df查看哪个…

Python列表基础

列表&#xff1a;创建列表:list[] 注意&#xff1a;列表里面类型可以是不同的类型 取值&#xff1a;list[2]   替换&#xff1a;注意不要越界(下表超出了可表示范围) 操作&#xff1a; 合并列表&#xff1a;   list3list2list1 列表的重复:   (list8*3)   判断元素是否…

树莓派 触摸屏_如何用树莓派搭建一个颗粒物(PM2.5)传感器

用树莓派、一个廉价的传感器和一个便宜的屏幕监测空气质量。-- Stephan Tetzel(作者)大约一年前&#xff0c;我写了一篇关于如何使用树莓派和廉价传感器测量 空气质量 的文章。我们这几年已在学校里和私下使用了这个项目。然而它有一个缺点&#xff1a;由于它基于无线/有线网&a…

shell 25个常用命令

1.列出所有目录使用量&#xff0c;并按大小排序。 ls|xargs du -h|sort -rn #不递归下级目录使用du -sh2.查看文件排除以#开关和空白行&#xff0c;适合查看配置文件。 egrep -v "^#|^$" filenamesed /#.*$/d; /^ *$/d3.删除空格和空行。 sed /^$/d filename #删除空…

tensorflow入门_TensorFlow法律和统计入门

tensorflow入门by Daniel Deutsch由Daniel Deutsch TensorFlow法律和统计入门 (Get started with TensorFlow on law and statistics) What this is about 这是关于什么的 What we will use 我们将使用什么 Get started 开始吧 Shell commands for installing everything you …

centos7 nginx+php5.6+mysql安装与配置

安装与配置 php 56的安装 php的配置写在 php.ini&#xff0c;可在phpinfo()中查看 //查找已安装 yum list installed | grep php // php卸载 yum -y remove php56* yum remove httpd* php* 可用的资源&#xff1a;centos 安装php56nginx nginx php-fpm nginx安装 sudo rpm -Uv…

leetcode337. 打家劫舍 III(dfs)

在上次打劫完一条街道之后和一圈房屋后&#xff0c;小偷又发现了一个新的可行窃的地区。这个地区只有一个入口&#xff0c;我们称之为“根”。 除了“根”之外&#xff0c;每栋房子有且只有一个“父“房子与之相连。一番侦察之后&#xff0c;聪明的小偷意识到“这个地方的所有房…

c语言面试题东软,2012东软笔试题

1、下列变量定义错误的是&#xff24;int a;double b4.5;boolean btrue;float f9.8; (9.8f)2、65%32的值是 D 3%53219103、对于一个三位的正整数 n&#xff0c;取出它的十位数字k(k为整型)的表达式是k n / 10 % 10k ( n - n / 100 * 100 )k n % 10k n / 104、下列语句序列执…

matlab肌电信号平滑滤波_MATLAB图像处理:43:用高斯平滑滤波器处理图像

本示例说明了如何使用imgaussfilt来对图像应用不同的高斯平滑滤波器。高斯平滑滤波器通常用于降低噪声。将图像读入工作区。I imread(cameraman.tif);使用各向同性的高斯平滑核增加标准偏差来过滤图像。高斯滤波器通常是各向同性的&#xff0c;也就是说&#xff0c;它们在两个…

Github 简明教程 - 添加远程库

现在的情景是&#xff0c;你已经在本地创建了一个Git仓库后&#xff0c;又想在GitHub创建一个Git仓库&#xff0c;并且让这两个仓库进行远程同步&#xff0c;这样&#xff0c;GitHub上的仓库既可以作为备份&#xff0c;又可以让其他人通过该仓库来协作&#xff0c;真是一举多得…

githooks_使用Githooks改善团队的开发工作流程

githooksby Daniel Deutsch由Daniel Deutsch 使用Githooks改善团队的开发工作流程 (Improve your team’s development workflow with Githooks) Every product that is developed by more than one programmer needs to have some guidelines to harmonize the workflow.由多…

分享AI有道干货 | 126 篇 AI 原创文章精选(ML、DL、资源、教程)

一年多来&#xff0c;公众号【AI有道】已经发布了 140 的原创文章了。内容涉及林轩田机器学习课程笔记、吴恩达 deeplearning.ai 课程笔记、机器学习、深度学习、笔试面试题、资源教程等等。值得一提的是每篇文章都是我用心整理的&#xff0c;编者一贯坚持使用通俗形象的语言给…

c语言qt生成dll与加载dll,Qt制作界面的DLL以及调用

1、将界面做成dll修改pro文件DEFINES WIDGETDLL_LIBRARYTEMPLATE lib修改头文件#if defined(WIDGETDLL_LIBRARY)# define WIDGETDLLSHARED_EXPORT Q_DECL_EXPORT#else# define WIDGETDLLSHARED_EXPORT Q_DECL_IMPORT#endifclass WIDGETDLLSHARED_EXPORT WidgetDll:public QWi…

leetcode1338. 数组大小减半(贪心算法)

给你一个整数数组 arr。你可以从中选出一个整数集合&#xff0c;并删除这些整数在数组中的每次出现。 返回 至少 能删除数组中的一半整数的整数集合的最小大小。 示例 1&#xff1a; 输入&#xff1a;arr [3,3,3,3,5,5,5,2,2,7] 输出&#xff1a;2 解释&#xff1a;选择 {3…

20162329 张旭升 2017 - 2018 《程序设计与数据结构》第五周总结

20162329 2017-2018-1 《程序设计与数据结构》第五周学习总结 教材学习内容总结 1.学习目标 了解集合的概念了解并使用抽象数据类型初步了解使用Java泛型学习栈这种数据结构用数组、链表实现栈2.学习内容 集合的概念&#xff1a; 集合是手机并组织其他对象的对象&#xff0c;他…

centos 安装trace_前期的准备工作-MacOS Mojave 10.14.3 下安装CentOS 7及Bochs 002

MacOS Mojave 10.14.3 下使用虚拟机安装CentOS 7 以及 Bochs 2.6.9CentOS 7.6.1810 系统下 安装Bochs 2.6.91 下载CentOS 7.6.1810网址为https://www.centos.org/遇到的问题安装后无法使用使用网络&#xff0c;最简单的解决方法就是增加一个新的网络适配器&#xff0c;使用Nat共…