此文仅为初学java的同学学习,大佬请勿喷,文末我会附上完整代码包供大家参考

redis的搭建教程此处略过,大家自行百度,本文的教程开始:

一、先在pom.xml中添加相关依赖

<!--redis的依赖 start-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!--redis的依赖 end-->

二、在application.yml中加入相关的配置

spring:
#redis配置(host和端口改成你自己的)
redis:
host: 10.24.19.237
port: 6379
# 密码,没有就不配置
password: 123456
# 连接超时时间(毫秒)
timeout: 36000
# Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
database: 0
lettuce:
pool:
# 连接池最大连接数(使用负值表示没有限制)默认 8
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
max-wait: -1ms
# 连接池中的最大空闲连接 默认 8
max-idle: 8
# 连接池中的最小空闲连接 默认 0
min-idle: 0

三、添加一个RedisTemplate的工具类RedisUtils.java方便我们使用

package com.example.study.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component; import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit; /**
* RedisTemplate 工具类
*
* @author 154594742@qq.com
* @date 2021/3/1 20:23
*/
@Component
public class RedisUtils { @Autowired
private RedisTemplate redisTemplate; //- - - - - - - - - - - - - - - - - - - - - 通用方法 - - - - - - - - - - - - - - - - - - - - /**
* 给一个指定的 key 值附加过期时间
*
* @param key
* @param time
* @return
*/
public boolean expire(String key, long time) {
return redisTemplate.expire(key, time, TimeUnit.SECONDS);
} /**
* 根据key进行删除
*
* @param key
* @return
*/
public boolean delete(String key) {
return redisTemplate.delete(key);
} /**
* 根据批量key进行批量删除
*
* @param keys
* @return 执行成功的数量
*/
public Long delete(Collection<String> keys) {
return redisTemplate.delete(keys);
} /**
* 根据key 获取过期时间
*
* @param key
* @return
*/
public long getTime(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
} /**
* 根据key 获取过期时间
*
* @param key
* @return
*/
public boolean hasKey(String key) {
return redisTemplate.hasKey(key);
} /**
* 移除指定key 的过期时间
*
* @param key
* @return
*/
public boolean persist(String key) {
return redisTemplate.boundValueOps(key).persist();
} //- - - - - - - - - - - - - - - - - - - - - String类型 - - - - - - - - - - - - - - - - - - - - /**
* 根据key获取值
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
} /**
* 将值放入缓存
*
* @param key 键
* @param value 值
* @return true成功 false 失败
*/
public void set(String key, String value) {
redisTemplate.opsForValue().set(key, value);
} /**
* 将值放入缓存并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) 小于等于0为无期限
* @return true成功 false 失败
*/
public void set(String key, String value, long time) {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
this.set(key, value);
}
} /**
* 批量添加 key (重复的键会覆盖)
*
* @param keyAndValue
*/
public void batchSet(Map<String, String> keyAndValue) {
redisTemplate.opsForValue().multiSet(keyAndValue);
} /**
* 批量添加 key-value 只有在键不存在时,才添加
* map 中只要有一个key存在,则全部不添加
*
* @param keyAndValue
*/
public void batchSetIfAbsent(Map<String, String> keyAndValue) {
redisTemplate.opsForValue().multiSetIfAbsent(keyAndValue);
} /**
* 对一个 key-value 的值进行加减操作,
* 如果该 key 不存在 将创建一个key 并赋值该 number
* 如果 key 存在,但 value 不是长整型 ,将报错
*
* @param key
* @param number
*/
public Long increment(String key, long number) {
return redisTemplate.opsForValue().increment(key, number);
} /**
* 对一个 key-value 的值进行加减操作,
* 如果该 key 不存在 将创建一个key 并赋值该 number
* 如果 key 存在,但 value 不是 纯数字 ,将报错
*
* @param key
* @param number
*/
public Double increment(String key, double number) {
return redisTemplate.opsForValue().increment(key, number);
} //- - - - - - - - - - - - - - - - - - - - - set类型 - - - - - - - - - - - - - - - - - - - - /**
* 将数据放入set缓存
*
* @param key 键
* @return
*/
public void sSet(String key, String value) {
redisTemplate.opsForSet().add(key, value);
} /**
* 获取变量中的值
*
* @param key 键
* @return
*/
public Set<Object> members(String key) {
return redisTemplate.opsForSet().members(key);
} /**
* 随机获取变量中指定个数的元素
*
* @param key 键
* @param count 值
* @return
*/
public void randomMembers(String key, long count) {
redisTemplate.opsForSet().randomMembers(key, count);
} /**
* 随机获取变量中的元素
*
* @param key 键
* @return
*/
public Object randomMember(String key) {
return redisTemplate.opsForSet().randomMember(key);
} /**
* 弹出变量中的元素
*
* @param key 键
* @return
*/
public Object pop(String key) {
return redisTemplate.opsForSet().pop(key);
} /**
* 获取变量中值的长度
*
* @param key 键
* @return
*/
public long size(String key) {
return redisTemplate.opsForSet().size(key);
} /**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
return redisTemplate.opsForSet().isMember(key, value);
} /**
* 检查给定的元素是否在变量中。
*
* @param key 键
* @param obj 元素对象
* @return
*/
public boolean isMember(String key, Object obj) {
return redisTemplate.opsForSet().isMember(key, obj);
} /**
* 转移变量的元素值到目的变量。
*
* @param key 键
* @param value 元素对象
* @param destKey 元素对象
* @return
*/
public boolean move(String key, String value, String destKey) {
return redisTemplate.opsForSet().move(key, value, destKey);
} /**
* 批量移除set缓存中元素
*
* @param key 键
* @param values 值
* @return
*/
public void remove(String key, Object... values) {
redisTemplate.opsForSet().remove(key, values);
} /**
* 通过给定的key求2个set变量的差值
*
* @param key 键
* @param destKey 键
* @return
*/
public Set<Set> difference(String key, String destKey) {
return redisTemplate.opsForSet().difference(key, destKey);
} //- - - - - - - - - - - - - - - - - - - - - hash类型 - - - - - - - - - - - - - - - - - - - - /**
* 加入缓存
*
* @param key 键
* @param map 键
* @return
*/
public void add(String key, Map<String, String> map) {
redisTemplate.opsForHash().putAll(key, map);
} /**
* 获取 key 下的 所有 hashkey 和 value
*
* @param key 键
* @return
*/
public Map<Object, Object> getHashEntries(String key) {
return redisTemplate.opsForHash().entries(key);
} /**
* 验证指定 key 下 有没有指定的 hashkey
*
* @param key
* @param hashKey
* @return
*/
public boolean hashKey(String key, String hashKey) {
return redisTemplate.opsForHash().hasKey(key, hashKey);
} /**
* 获取指定key的值string
*
* @param key 键
* @param key2 键
* @return
*/
public String getMapString(String key, String key2) {
return redisTemplate.opsForHash().get(key, key2).toString();
} /**
* 获取指定的值Int
*
* @param key 键
* @param key2 键
* @return
*/
public Integer getMapInt(String key, String key2) {
return (Integer) redisTemplate.opsForHash().get(key, key2);
} /**
* 弹出元素并删除
*
* @param key 键
* @return
*/
public String popValue(String key) {
return redisTemplate.opsForSet().pop(key).toString();
} /**
* 删除指定 hash 的 HashKey
*
* @param key
* @param hashKeys
* @return 删除成功的 数量
*/
public Long delete(String key, String... hashKeys) {
return redisTemplate.opsForHash().delete(key, hashKeys);
} /**
* 给指定 hash 的 hashkey 做增减操作
*
* @param key
* @param hashKey
* @param number
* @return
*/
public Long increment(String key, String hashKey, long number) {
return redisTemplate.opsForHash().increment(key, hashKey, number);
} /**
* 给指定 hash 的 hashkey 做增减操作
*
* @param key
* @param hashKey
* @param number
* @return
*/
public Double increment(String key, String hashKey, Double number) {
return redisTemplate.opsForHash().increment(key, hashKey, number);
} /**
* 获取 key 下的 所有 hashkey 字段
*
* @param key
* @return
*/
public Set<Object> hashKeys(String key) {
return redisTemplate.opsForHash().keys(key);
} /**
* 获取指定 hash 下面的 键值对 数量
*
* @param key
* @return
*/
public Long hashSize(String key) {
return redisTemplate.opsForHash().size(key);
} //- - - - - - - - - - - - - - - - - - - - - list类型 - - - - - - - - - - - - - - - - - - - - /**
* 在变量左边添加元素值
*
* @param key
* @param value
* @return
*/
public void leftPush(String key, Object value) {
redisTemplate.opsForList().leftPush(key, value);
} /**
* 获取集合指定位置的值。
*
* @param key
* @param index
* @return
*/
public Object index(String key, long index) {
return redisTemplate.opsForList().index(key, index);
} /**
* 获取指定区间的值。
*
* @param key
* @param start
* @param end
* @return
*/
public List<Object> range(String key, long start, long end) {
return redisTemplate.opsForList().range(key, start, end);
} /**
* 把最后一个参数值放到指定集合的第一个出现中间参数的前面,
* 如果中间参数值存在的话。
*
* @param key
* @param pivot
* @param value
* @return
*/
public void leftPush(String key, String pivot, String value) {
redisTemplate.opsForList().leftPush(key, pivot, value);
} /**
* 向左边批量添加参数元素。
*
* @param key
* @param values
* @return
*/
public void leftPushAll(String key, String... values) {
redisTemplate.opsForList().leftPushAll(key, values);
} /**
* 向集合最右边添加元素。
*
* @param key
* @param value
* @return
*/
public void leftPushAll(String key, String value) {
redisTemplate.opsForList().rightPush(key, value);
} /**
* 向左边批量添加参数元素。
*
* @param key
* @param values
* @return
*/
public void rightPushAll(String key, String... values) {
redisTemplate.opsForList().rightPushAll(key, values);
} /**
* 向已存在的集合中添加元素。
*
* @param key
* @param value
* @return
*/
public void rightPushIfPresent(String key, Object value) {
redisTemplate.opsForList().rightPushIfPresent(key, value);
} /**
* 向已存在的集合中添加元素。
*
* @param key
* @return
*/
public long listLength(String key) {
return redisTemplate.opsForList().size(key);
} /**
* 移除集合中的左边第一个元素。
*
* @param key
* @return
*/
public void leftPop(String key) {
redisTemplate.opsForList().leftPop(key);
} /**
* 移除集合中左边的元素在等待的时间里,如果超过等待的时间仍没有元素则退出。
*
* @param key
* @return
*/
public void leftPop(String key, long timeout, TimeUnit unit) {
redisTemplate.opsForList().leftPop(key, timeout, unit);
} /**
* 移除集合中右边的元素。
*
* @param key
* @return
*/
public void rightPop(String key) {
redisTemplate.opsForList().rightPop(key);
} /**
* 移除集合中右边的元素在等待的时间里,如果超过等待的时间仍没有元素则退出。
*
* @param key
* @return
*/
public void rightPop(String key, long timeout, TimeUnit unit) {
redisTemplate.opsForList().rightPop(key, timeout, unit);
}
}

四、添加RedisController.java类来测试一下

package com.example.study.controller;

import com.example.study.model.vo.ResponseVo;
import com.example.study.util.BuildResponseUtils;
import com.example.study.util.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; /**
* redis控制器
*
* @author 154594742@qq.com
* @date 2021/3/1 19:50
*/ @RequestMapping("/redis")
@RestController
@Api(tags = "Redis控制器")
public class RedisController { @Autowired
private RedisUtils redisUtils; /**
* 设置缓存
*
* @param key key
* @param value value
* @return ResponseVo
*/
@ApiOperation("设置缓存")
@PostMapping("add")
public ResponseVo<?> add(String key, String value) {
redisUtils.set(key, value, 600);
return BuildResponseUtils.success();
} /**
* 通过key查询
*
* @param key key
* @return ResponseVo
*/
@ApiOperation("通过key查询")
@GetMapping("{key}")
public ResponseVo<Object> getByKey(@PathVariable String key) {
String value = (String) redisUtils.get(key);
return BuildResponseUtils.buildResponse(value);
} /**
* 通过key删除
*
* @param key key
* @return ResponseVo
*/
@ApiOperation("通过key删除")
@DeleteMapping("{key}")
public ResponseVo<?> delete(@PathVariable String key) {
return redisUtils.delete(key) ? BuildResponseUtils.success() : BuildResponseUtils.error();
}
}

五、运行项目,然后访问 http://localhost:8080/swagger-ui.html 测试一下效果吧

设置缓存:

获取缓存:

六、附上完整代码包供大家学习参考,如果对你有帮助,请给个关注或者点个赞吧! 点击下载完整代码包

手把手教你SpringBoot2整合Redis的更多相关文章

  1. SpringBoot2整合Redis缓存

    遵循SpringBoot三板斧 第一步加依赖 <!-- Redis --> <dependency> <groupId>org.springframework.bo ...

  2. 手把手教你 基础 整合最优雅SSM框架:SpringMVC + Spring

    我们看招聘信息的时候,经常会看到这一点,需要具备SSH框架的技能:而且在大部分教学课堂中,也会把SSH作为最核心的教学内容. 但是,我们在实际应用中发现,SpringMVC可以完全替代Struts,配 ...

  3. SpringBoot2整合Redis多数据源

    配置文件属性 spring: redis: database: 1 host: 192.168.50.144 port: 6379 password: timeout: 600 #Springboot ...

  4. 【轮子狂魔】手把手教你自造Redis Client

    为什么做Redis Client? Redis Client顾名思义,redis的客户端,主要是封装了一些对于Redis的操作. 而目前用的比较广泛的 ServiceStack.Redis 不学好,居 ...

  5. springboot2 整合redis

    1.添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  6. SpringBoot2整合Redis

    pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  7. SpringBoot2.x整合Redis实战 4节课

    1.分布式缓存Redis介绍      简介:讲解为什么要用缓存和介绍什么是Redis,新手练习工具 1.redis官网 https://redis.io/download          2.新手 ...

  8. 小D课堂 - 零基础入门SpringBoot2.X到实战_第9节 SpringBoot2.x整合Redis实战_39、SpringBoot2.x整合redis实战讲解

    笔记 3.SpringBoot2.x整合redis实战讲解 简介:使用springboot-starter整合reids实战 1.官网:https://docs.spring.io/spring-bo ...

  9. 手把手教你用redis实现一个简单的mq消息队列(java)

    众所周知,消息队列是应用系统中重要的组件,主要解决应用解耦,异步消息,流量削锋等问题,实现高性能,高可用,可伸缩和最终一致性架构.目前使用较多的消息队列有 ActiveMQ,RabbitMQ,Zero ...

随机推荐

  1. 2019CCPC厦门站总结

    这是一篇打铁游记~ $day1$ 坐动车去厦门,三个人买了一堆零食,吃了一路,除了睡觉嘴巴基本就没停过.当然,我们到酒店后也去吃了烧烤,我们虽然是在岛外的厦门北站的下的,还是很幸运的找到一家好吃了,乌 ...

  2. Codeforces Global Round 11 C. The Hard Work of Paparazzi(dp/最长上升子序列)

    题目链接:https://codeforces.com/contest/1427/problem/C 题意 \(r\) 行与 \(r\) 列相交形成了 \(r \times r\) 个点,初始时刻记者 ...

  3. codeforces#244(div.2) C

    动漫节一游回来之后一直处于一种意识模糊的状态 看到大家都陆陆续续地过了C心里还是有点着急(自己没思路啊囧) 其实当时就在想该如何找到DFS中的一个环,然后再找到环路上最小的一个值 把所有环路上最小的值 ...

  4. Codeforces Round #625 (Div. 2, based on Technocup 2020 Final Round) D. Navigation System(有向图,BFS,最短路)

    题意: n 点 m 边有向图,给出行走路径,求行走途中到路径终点最短路变化次数的最小值和最大值 . 思路 : 逆向广搜,正向模拟. #include <bits/stdc++.h> usi ...

  5. 【uva 1515】Pool construction(图论--网络流最小割 模型题)

    题意:有一个水塘,要求把它用围栏围起来,每个费用为b.其中,(#)代表草,(.)代表洞,把一个草变成洞需要费用d, 把一个洞变成草需要费用f.请输出合法方案中的最小费用. 解法:(不好理解...... ...

  6. hdu 6863 Isomorphic Strings 哈希+求公因子

    题意: t组输入,每组数据输入一个整数n,代表字符串长度.下面再输入一个字符串 你需要判断这个字符串能不能分成大于1段,且这些段的最小表示法是一样的 例如:abccab,它可以分成2段,分别是abc和 ...

  7. 使用SignTool对软件安装包进行数字签名(一)--制作证书

    一.制作根证书 1.开始菜单-运行-输入cmd,弹出命令行窗体. 2.输入命令:cd /d F:\SignTool,将当前工作目录修改到SignTool路径下. 3.使用makecert命令制作证书, ...

  8. Gym 101170F Free Weights(二分)题解

    题意:给出两行,每一行都有n个数组,一共有2 * n个,大小为1~n,每个有两个.现在可以进行操作:拿出一个物品i,然后放到一个空格,花费i.可以任意平移物品,平移没有花费.每一行空间无限.要求你把一 ...

  9. Set DSL in Ubuntu 18.04

    Reference Solutions: Ctrl+Atl+t Type nmcli con edit type pppoe con-name ANY_NAME_OF_DSL_YOU_LIKE, wh ...

  10. VuePress config All In One

    VuePress config All In One docs/.vuepress/config.js const { title, description, } = require('../../p ...