目录

  • 简介
    • redis基本结构:
  • 代码实现
    • 1.新建Springboot项目,添加必要的依赖 pom.xml:
    • 2. 在application.yml配置文件中添加 redis的相关配置
    • 3.SpringBoot 添加 自定义 redis 配置类
    • 4.创建redis工具类
    • 5.User 实体类
    • 6.redis使用实例(以存取为例):
    • 7.启动项目,进行测试

简介

Redis 是完全开源的,遵守 BSD 协议,是一个高性能的 key-value 数据库。

Redis 与其他 key - value 缓存产品有以下三个特点

  • Redis支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用。
  • Redis不仅仅支持简单的key-value类型的数据,同时还提供list,set,zset,hash等数据结构的存储。
  • Redis支持数据的备份,即master-slave模式的数据备份。

redis基本结构:

  • String: 字符串
  • Hash: 散列
  • List: 列表
  • Set: 集合
  • Sorted Set: 有序集合

代码实现

1.新建Springboot项目,添加必要的依赖 pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.3</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>org.springblade</groupId><artifactId>spd-hisserview-ymf</artifactId><version>0.0.1-SNAPSHOT</version><name>spd-hisserview-ymf</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><!--        多数据源配置--><dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.3.1</version></dependency><!--        mysql依赖--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- 引入 redis 依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><!-- 默认指定了lettuce,我们需要排除 ,并且引入jedis的客户端--><exclusions><exclusion><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId></exclusion></exclusions></dependency><!-- jedis的客户端 --><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency><!--sqlserver数据库JDBC连接依赖--><dependency><groupId>com.microsoft.sqlserver</groupId><artifactId>sqljdbc4</artifactId><version>4.0</version></dependency><!--MyBatisPlus启动依赖--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.2.0</version></dependency><!--Oracle数据库JDBC连接依赖--><dependency><groupId>com.oracle</groupId><artifactId>ojdbc7</artifactId><version>12.2.0.1</version></dependency><!--JUNIT测试相关--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>

2. 在application.yml配置文件中添加 redis的相关配置

server:port: 81spring:redis:#Redis配置host: 127.0.0.1##redis端口号port: 6379##redis密码password:##redis连接超时时间(毫秒)timeout: 60000##Redis默认情况下有16个分片,这里配置具体使用的分片,默认时0database: 10application:name: viewServicedatasource:dynamic:primary: bdsz #设置默认的数据源或者数据源组,默认值即为masterstrict: true #设置严格模式,默认false不启动. 启动后在未匹配到指定数据源时候会抛出异常,不启动则使用默认数据源.datasource:bdsz:driver-class-name: oracle.jdbc.driver.OracleDriver#    本地连接url: jdbc:oracle:thin:@//localhost:1521/orclusername: SYSTEMpassword: 961008Dyh#    远程连接
#          url: jdbc:oracle:thin:@//100.100.100.45:1521/PDBORCL
#          username: BDFPQS
#          password: BDFPQS123456szey:driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver#    本地连接url: jdbc:sqlserver://localhost:1433;databaseName=testusername: sapassword: 961008#    远程连接
#          url: jdbc:sqlserver://192.168.170.186:1433;databaseName=HERP
#          username: hrp_ymf
#          password: hrp_ymf#mybatis-plus配置控制台打印完整带参数SQL语句
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpltenantId:szey: 100000bdsz: 200000

3.SpringBoot 添加 自定义 redis 配置类

package org.springblade.config;/*** @ClassName: RedisConfig* @author: 〆、dyh* @since: 2022/4/2 15:36*/import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;/*** 使用jedis整合redis*/
@Data
@Configuration
public class RedisConfig {private static Logger logger = LoggerFactory.getLogger(RedisConfig.class);@Value("${spring.redis.host}")private String host;@Value("${spring.redis.port}")private int port;@Value("${spring.redis.password}")private String password;@Value("${spring.redis.timeout}")private int timeout;@Beanpublic JedisPool redisPoolFactory() throws Exception {logger.info("JedisPool 注入成功!");logger.info("redis地址:" + host + ":" + port);JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();//是否启用pool的jmx管理功能,默认truejedisPoolConfig.setJmxEnabled(true);JedisPool JedisPool;if (StringUtils.hasText(password)) {JedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);} else {JedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);}logger.info("JedisPool:" + JedisPool);return JedisPool;}
}

4.创建redis工具类

package org.springblade.util;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;/*** @ClassName: RedisUtil* @author: 〆、dyh* @since: 2022/4/2 15:43*/@Component
public class RedisUtil {@Autowiredprivate JedisPool jedisPool;@Value("${spring.redis.database}")private String database;//设置为0就是永不过期  单位秒private int expire = 0;/*** 获取Jedis实例** @return*/public synchronized Jedis getJedis() {try {if (jedisPool != null) {Jedis resource = jedisPool.getResource();resource.select(Integer.parseInt(database)); //设置为第10个库(db) spring.redis.databasereturn resource;} else {System.out.println("获取的Redis链接为null");return null;}} catch (Exception e) {e.printStackTrace();System.out.println("获取Redis链接出错:" + e.getMessage());return null;}}/*** get value from redis** @param key* @return*/public byte[] get(byte[] key) {Jedis jedis = getJedis();byte[] value = null;try {value = jedis.get(key);} finally {jedis.close();}return value;}/*** get value from redis** @param key* @return*/public String get(String key) {Jedis jedis = getJedis();String value = null;try {value = jedis.get(key);} finally {jedis.close();}return value;}/*** set** @param key* @param value* @return*/public void set(byte[] key, byte[] value) {Jedis jedis = getJedis();try {jedis.set(key, value);if (expire != 0) {jedis.expire(key, expire);}} finally {jedis.close();}}/*** set** @param key* @param value* @return*/public void set(String key, String value) {Jedis jedis = getJedis();try {jedis.set(key, value);if (expire != 0) {jedis.expire(key, expire);}} finally {jedis.close();}}/*** set** @param key* @param value* @param expire* @return*/public void set(byte[] key, byte[] value, int expire) {Jedis jedis = getJedis();try {jedis.set(key, value);if (expire != 0) {jedis.expire(key, expire);}} finally {jedis.close();}}/*** 添加key=String,value=HashMap<String,String>类型的数据 hmset** @param key* @param inMap* @param expire 生命周期 单位秒*/public void hmset(String key, Map<String, String> inMap, int expire) {Jedis jedis = getJedis();try {jedis.hmset(key, inMap);if (expire != 0) {jedis.expire(key, expire);}} finally {jedis.close();}}/*** 获取value类型为HashMap<String,String>类型的数据** @param key* @return*/public Map<String, String> hgetAll(String key) {Jedis jedis = getJedis();Map<String, String> value = null;try {value = jedis.hgetAll(key);} finally {jedis.close();}return value;}/*** del** @param key*/public void del(byte[] key) {Jedis jedis = getJedis();try {jedis.del(key);} finally {jedis.close();}}/*** del** @param key*/public void del(String key) {Jedis jedis = getJedis();try {jedis.del(key);} finally {jedis.close();}}/*** 判断指定键是否存在** @param key* @return*/public boolean exists(String key) {Jedis jedis = getJedis();boolean flag = jedis.exists(key);jedis.close();return flag;}/*** 获取key对应的值剩余存活时间** @param key* @return 正数:剩余的时间(秒) 负数:已过期*/public Long ttlKey(String key) {Jedis jedis = getJedis();try {return jedis.ttl(key);} catch (Exception e) {System.out.println(" -- Redis 获取key对应的值剩余存活时间出错,出错原因:" + e);e.printStackTrace();return 0L;} finally {jedis.close();}}/*** 获取key对应的值剩余存活时间** @param key* @return 正数:剩余的时间(秒) 负数:已过期*/public Long ttlKey(byte[] key) {Jedis jedis = getJedis();try {return jedis.ttl(key);} catch (Exception e) {System.out.println(" -- Redis 获取key对应的值剩余存活时间出错,出错原因:" + e);e.printStackTrace();return 0L;} finally {jedis.close();}}/*** 存储对象** @param key* @param obj* @param expire*/public void setObject(String key, Object obj, int expire) {Jedis jedis = getJedis();byte[] data = ObjTOSerialize(obj);jedis.set(key.getBytes(), data);if (expire != 0) {jedis.expire(key, expire);}jedis.close();}/*** 获取对象** @param key* @return*/public Object getObject(String key) {Jedis jedis = getJedis();byte[] data = jedis.get(key.getBytes());Object obj = null;if (data != null) {obj = unSerialize(data);}jedis.close();return obj;}/*** 序列化一个对象** @param obj* @return*/public byte[] ObjTOSerialize(Object obj) {ObjectOutputStream oos = null;ByteArrayOutputStream byteOut = null;try {byteOut = new ByteArrayOutputStream();oos = new ObjectOutputStream(byteOut);oos.writeObject(obj);byte[] bytes = byteOut.toByteArray();return bytes;} catch (Exception e) {System.out.println("-- Redis序列化对象出错:" + e);e.printStackTrace();}return null;}/*** 反序列化一个对象** @param bytes* @return*/public Object unSerialize(byte[] bytes) {ByteArrayInputStream in = null;try {in = new ByteArrayInputStream(bytes);ObjectInputStream objIn = new ObjectInputStream(in);return objIn.readObject();} catch (Exception e) {System.out.println("-- Redis反序列化对象出错:" + e);e.printStackTrace();}return null;}
}

5.User 实体类

package org.springblade.entity;import lombok.Data;import java.io.Serializable;import lombok.Data;import java.io.Serializable;/*** @ClassName: User * @author: 〆、dyh* @since: 2022/4/3 19:58*/
@Data
public class User implements Serializable {/*** 序列化*/private static final long serialVersionUID = -4938532764925446470L;private Integer user_id;private String openid;private String user_name;private String user_phone;
}

6.redis使用实例(以存取为例):

在需要redis存取的类中,注入RedisUtil ,然后使用 redisUtil 对象调用 存取 方法。

package org.springblade.controller;import org.springblade.entity.User;
import org.springblade.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.Map;/*** @ClassName: UserController* @author: 〆、dyh* @since: 2022/4/3 19:58*/@RestController
@RequestMapping("/user")
public class UserController {/*** 初始3rd_session有效期 单位s  有效期为一天*/private static final int expire = 60 * 60 * 24;/*** 注入 RedisUtil*/@Autowiredprivate RedisUtil redisUtil;/*** 获取用户策略:先从缓存中获取用户,没有则取数据表中的数据,再将数据写入缓存** @param userId* @return*/@GetMapping("/getData")public Map<String, String> getUserInfoById(String userId) {String userKey = "user_" + userId;//从redis存储中取所需数据Map<String, String> redisDataMap = redisUtil.hgetAll(userKey);if (redisDataMap == null || redisDataMap.size() == 0) {System.out.println("缓存不存在");//缓存不存在//模拟从数据库中获取用户信息User userInfo = new User();userInfo.setUser_id(1);userInfo.setUser_name("张三");userInfo.setUser_phone("15720821396");//把用户信息存入redis中redisDataMap.put("user_id", String.valueOf(userInfo.getUser_id()));redisDataMap.put("user_name", String.valueOf(userInfo.getUser_name()));redisDataMap.put("user_phone", String.valueOf(userInfo.getUser_phone()));//插入缓存redisUtil.hmset(userKey, redisDataMap, expire);} else {System.out.println("缓存存在,用户信息:" + redisDataMap.toString());}return redisDataMap;}
}

7.启动项目,进行测试

在浏览器中输入http://localhost:81/user/getData?userId=1,第一次访问:

再次访问:

SpringBoot 使用jedis整合redis实现缓存处理相关推荐

  1. springboot整合redis做缓存

    之前的项目中,用到过redis,主要是使用redis做缓存,redis在web开发中使用的场景很多,其中缓存是其中一个很重要的使用场景,之所以用作缓存,得益于redis的读写数据,尤其是在读取数据的时 ...

  2. Springboot整合redis实现缓存及其缓存运行原理浅析

    声明:小白,学习阶段,主要目的是为了记录学习过程,本文仅供参考,如有不足的地方欢迎指出讨论交流 本文基于Springboot2.1.3版本开发: 准备阶段 首先是pom.xml文件所需的依赖: < ...

  3. 商城项目(二)整合Redis实现缓存功能

    整合Redis实现缓存功能 环境搭建 Redis 版本:5.0.4 SpringBoot整合Redis 添加项目依赖 <!--redis依赖配置--> <dependency> ...

  4. spring boot使用Jedis整合Redis

    文章目录 spring boot使用jedis整合redis 总结 Spring Boot整合Redis有两种方式,分别是Jedis和RedisTemplate,那么它们二者有什么区别呢? 1.Jed ...

  5. 项目总结10:通过反射解决springboot环境下从redis取缓存进行转换时出现ClassCastException异常问题...

    通过反射解决springboot环境下从redis取缓存进行转换时出现ClassCastException异常问题 关键字 springboot热部署  ClassCastException异常 反射 ...

  6. springboot整个缓存_SpringBoot中整合Redis(缓存篇)

    实际开发中缓存处理是必须的,不可能我们每次客户端去请求一次服务器,服务器每次都要去数据库中进行查找,为什么要使用缓存?说到底是为了提高系统的运行速度.将用户频繁访问的内容存放在离用户最近,访问速度最快 ...

  7. mysql springboot 缓存_Spring Boot 整合 Redis 实现缓存操作

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 产品没有价值,开发团队再优秀也无济于事 – <启示录> 』 本文提纲 一.缓 ...

  8. SpringBoot整合Redis实现缓存、队列、广播

    [提前声明] 文章由作者:张耀峰 结合自己生产中的使用经验整理,最终形成简单易懂的文章 写作不易,转载请注明,谢谢! spark代码案例地址: https://github.com/Mydreaman ...

  9. Spring Boot 整合Redis 实现缓存

    本文提纲 一.缓存的应用场景 二.更新缓存的策略 三.运行 springboot-mybatis-redis 工程案例 四.springboot-mybatis-redis 工程代码配置详解 运行环境 ...

最新文章

  1. Java NIO系列教程(九) ServerSocketChannel
  2. Paddle 网络中的Tensor 数据结构
  3. 迭代与递归实现无限级分类
  4. postman自动打开_postman第1讲-开篇:介绍与安装
  5. YBTOJ:卖猪问题(网络流)
  6. 尚硅谷李老师Mysql基础笔记
  7. MySQL5.7数据库软件下载教程
  8. vi测试仪维修成功率高吗?_欧森杰检测仪:臭氧检测仪的六大特点,您真的了解吗?...
  9. 实验一 winrunner的安装使用
  10. 剧情插件Cutscene Creator uSequencer 1.3.7.1使用说明一
  11. python爬虫 - 爬取堆糖图片
  12. wlh- beagle bone 通过uboot tftp 加载zImage 设备树 及 nfs 挂载根文件系统
  13. Package pdftex.def Error: PDF mode expected, but DVI mode detected!
  14. Redis Srem 命令
  15. 本地通用验证码识别DLL/通用滑块识别/文字点选/图标点选/OCR文字识别/本地识别DLL
  16. git 拉取远程分支报错(fatal: ''xxx is not a commit and a branch '' cannot be created from it)
  17. Pycharm下同一目录py文件不能相互调用?
  18. Ubuntu12更新重启之后,只在左上角出现一闪一闪的小横杠
  19. Ultra Wideband Wireless Communication
  20. 【评测】iPS细胞株-Alzheimer‘s disease (AD),LDLR和APOE4基因突变

热门文章

  1. 频谱分析幅值单位_示波器FFT查看信号频谱和设置的方法
  2. 怎样推算是哪个世纪,哪个年代?
  3. 会的多和会的精,你会选哪个
  4. 信息增益以及增益率划分属性
  5. 企业全网电子商务营销方案(1)
  6. C++高阶必会操作--模板元编程
  7. “人、机、料、法、环、测”
  8. 在U盘安装Windows系统,Mac电脑期待已久的工具WTG
  9. HTML标签textarea去除红色下划线
  10. 2021-09-03 网安实验-文件修复-Stegano练习之隐写5