Redis(Jedis和SpringBoot整合Redis)

文章目录

    • 1.Jedis
        • 1.介绍
        • 2.环境配置
          • 1.创建maven项目
          • 2.pom.xml引入依赖
          • 3.新建一个包并创建一个文件
        • 3.Jedis远程连接到Redis
          • 1.Redis放到服务器可以连接的前提条件
          • 2.为Redis设置密码
            • 1.编辑配置文件
            • 2.找到 requirepass
            • 3.设置密码为root
            • 4.重启Redis,在shutdown的时候报错,原因是之前连接到了redis的客户端没有关闭,执行下面的指令关闭
            • 5.然后再重启Redis,此时再次操作Redis就需要密码了
          • 3.编写代码连接Redis
        • 4.key操作
          • 1.代码
          • 2.结果
        • 5.string操作
          • 1.代码
          • 2.结果
        • 6.list操作
          • 1.代码
          • 2.结果
        • 7.set操作
          • 1.代码
          • 2.结果
        • 8.hash操作
          • 1.代码
          • 2.结果
        • 9.zset操作
          • 1.代码
          • 2.结果
    • 2.由于Redis被攻击了,所以重新配置
        • 1.修改端口为7489
        • 2.设置redis密码
        • 3.使redis支持远程访问
        • 4.重启redis
          • 1.指定配置文件启动redis
          • 2.查看是否启动
          • 3.指定端口连接redis
          • 4.测试密码
          • 5.如果要关闭redis,在命令行关闭redis,输入shutdown
        • 5.开放7489端口
          • 1.宝塔开启端口
          • 2.腾讯云开启端口
          • 3.为了安全只允许本机ip访问
    • 2.SpringBoot2整合Redis
        • 1.环境配置
          • 1.创建maven项目
          • 2.pom.xml引入依赖
          • 3.application.yml 配置redis
          • 4.添加Redis的配置类(使用SpringBoot默认的会出些问题关于序列化的)RedisConfig.java
        • 2.测试
          • 1.编写测试的Controller
          • 2.编写主启动类
          • 3.启动测试 [localhost:8080/redisTest/set](http://localhost:8080/redisTest/set)
        • 3.对list进行操作
          • 1.代码
          • 2.结果
        • 4.注意事项
          • 1.先看报错是无法识别的token
          • 2.如果使用redisTemplate进行set会先序列化,然后读取的时候也会反序列化,但是直接在客户端set不会进行序列化,所以在使用redisTemplate进行反序列化的时候就会出现问题
          • 3.解决方式:都使用程序进行操作即可

1.Jedis

1.介绍

image-20240429154127142

2.环境配置
1.创建maven项目

image-20240429154831864

2.pom.xml引入依赖
    <dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>3.2.0</version></dependency>
3.新建一个包并创建一个文件

image-20240429155409891

3.Jedis远程连接到Redis
1.Redis放到服务器可以连接的前提条件
  • 确认端口开启
  • protected-mode(设置no支持远程访问)
  • 注销bind = 127.0.0.1
  • 最好设置一个密码在requirepass
2.为Redis设置密码
1.编辑配置文件
vim /etc/redis.conf
2.找到 requirepass

image-20240429160256016

3.设置密码为root

image-20240429160319448

4.重启Redis,在shutdown的时候报错,原因是之前连接到了redis的客户端没有关闭,执行下面的指令关闭
redis-cli shutdown nosave
5.然后再重启Redis,此时再次操作Redis就需要密码了

image-20240429163024650

3.编写代码连接Redis
package com.sun.jedis;import org.junit.Test;
import redis.clients.jedis.Jedis;/*** Description:** @Author sun* @Create 2024/4/29 15:53* @Version 1.0*/
public class Jedis_ {// 连接redis@Testpublic void con() {// 连接服务器的redis命令行Jedis jedis = new Jedis("xxxx", xxx);// 如果redis设置了密码要先进行验证jedis.auth("root");String ping = jedis.ping();System.out.println("ping = " + ping);// 关闭命令行连接jedis.close();}
}

image-20240429163739569

4.key操作
1.代码
    @Testpublic void key() {// 连接服务器的redis命令行Jedis jedis = new Jedis("xxxxxx", xxxx);// 如果redis设置了密码要先进行验证jedis.auth("root");// 设置keyjedis.set("k1", "v1");jedis.set("k2", "v2");jedis.set("k3", "v3");// 获取所有的keySet<String> keys = jedis.keys("*");// 遍历输出for (String key : keys) {System.out.println("key=" + key);}// 判断key是否存在Boolean k1 = jedis.exists("k1");System.out.println("k1是否存在?" + k1);// 查看key的ttlSystem.out.println("k2的ttl=" + jedis.ttl("k2"));// 获取值String k3 = jedis.get("k3");System.out.println("k3=" + k3);jedis.close();}
2.结果

image-20240429165247069

5.string操作
1.代码
    @Testpublic void string() {// 连接服务器的redis命令行Jedis jedis = new Jedis("xxxxxx", xxxx);// 如果redis设置了密码要先进行验证jedis.auth("root");// 先清除一下库jedis.flushDB();// 批量设置stringjedis.mset("k1", "v1", "k2", "v2", "k3", "v3");// 批量获取stringList<String> mget = jedis.mget("k1", "k2", "k3");for (String s : mget) {System.out.println(s);}jedis.close();}
2.结果

image-20240429165825709

6.list操作
1.代码
    @Testpublic void list() {// 连接服务器的redis命令行Jedis jedis = new Jedis("xxxxxx", xxxx);// 如果redis设置了密码要先进行验证jedis.auth("root");// 先清除一下库jedis.flushDB();// 向list的左边添加三条记录jedis.lpush("key", "v1", "v2", "v3");// 显示数据,应该是v3,v2,v1List<String> key = jedis.lrange("key", 0, -1);for (String s : key) {System.out.println(s);}jedis.close();}
}
2.结果

image-20240429170559212

7.set操作
1.代码
    @Testpublic void set() {// 连接服务器的redis命令行Jedis jedis = new Jedis("xxxxxx", xxxx);// 如果redis设置了密码要先进行验证jedis.auth("root");// 先清除一下库jedis.flushDB();// 向set中添加元素jedis.sadd("key", "val1", "val2", "val3");// 取出set中的所有值Set<String> key = jedis.smembers("key");// 遍历输出for (String s : key) {System.out.println(s);}jedis.close();}
2.结果

image-20240429170951539

8.hash操作
1.代码
    @Testpublic void hash() {// 连接服务器的redis命令行Jedis jedis = new Jedis("xxxxxx", xxxx);// 如果redis设置了密码要先进行验证jedis.auth("xxxxxxx");// 先清除一下库jedis.flushDB();// 向hash中设置值Map<String, String> map = new HashMap<String, String>();map.put("field1", "value1");map.put("field2", "value2");map.put("field3", "value3");jedis.hset("key", map);List<String> hmget = jedis.hmget("key", "field1", "field2", "field3");for (String s : hmget) {System.out.println(s);}jedis.close();}
2.结果

image-20240429205900768

9.zset操作
1.代码
    @Testpublic void zset() {// 连接服务器的redis命令行Jedis jedis = new Jedis("xxxx", xxxx);// 如果redis设置了密码要先进行验证jedis.auth("xxxx");// 先清除一下库jedis.flushDB();// 向zset中添加数据jedis.zadd("key", 1, "zhangsan");jedis.zadd("key", 2, "lisi");jedis.zadd("key", 3, "wangwu");// 取出数据Set<String> key = jedis.zrange("key", 0, -1);for (String s : key) {System.out.println(s);}jedis.close();}
2.结果

image-20240429210607348

2.由于Redis被攻击了,所以重新配置

1.修改端口为7489

image-20240429200416739

2.设置redis密码

image-20240429195814069

3.使redis支持远程访问

image-20240429200002355

image-20240429200046964

4.重启redis
1.指定配置文件启动redis
/usr/local/bin/redis-server /etc/redis.conf
2.查看是否启动
ps -aux | grep redis

image-20240429200524755

3.指定端口连接redis
/usr/local/bin/redis-cli -p 7489

image-20240429200655032

4.测试密码

image-20240429200728881

5.如果要关闭redis,在命令行关闭redis,输入shutdown
5.开放7489端口
1.宝塔开启端口
systemctl start firewalld && firewall-cmd --permanent --add-port=7489/tcp && firewall-cmd --reload && firewall-cmd --query-port=7489/tcp

image-20240429201337740

2.腾讯云开启端口

image-20240429201549924

3.为了安全只允许本机ip访问

image-20240429205215949

2.SpringBoot2整合Redis

1.环境配置
1.创建maven项目

image-20240429211111679

2.pom.xml引入依赖
    <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.6</version><relativePath/> <!-- lookup parent from repository --></parent><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><!-- 说 明 : 如 果 这 里 是 spring-boot-start 就 改 成 如 下spring-boot-start-web--><artifactId>spring-boot-starter-web</artifactId></dependency><!-- redis --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!-- spring2.X 集成 redis 所需 common-pool--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><!--不要带版本号,防止冲突--></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><version>2.13.2.2</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
3.application.yml 配置redis
spring:redis:host: xxxxxx # Redis服务器地址port: xxxx# Redis服务器端口password: ****** # Redis服务器密码database: 0 # 默认数据库为0号timeout: 1800000 # 连接超时时间是1800秒lettuce:pool:max-active: 20 # 最大活跃连接数,使用负值表示没有限制max-wait: -1 # 最大等待时间,单位为毫秒,使用负值表示没有限制max-idle: 10 # 最大空闲连接数min-idle: 0 # 最小空闲连接数        
4.添加Redis的配置类(使用SpringBoot默认的会出些问题关于序列化的)RedisConfig.java
package com.sun.redis.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;import java.time.Duration;/*** Description:** @Author sun* @Create 2024/4/29 21:29* @Version 1.0*/
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {RedisTemplate<String, Object> template =new RedisTemplate<>();System.out.println("template=>" + template);RedisSerializer<String> redisSerializer =new StringRedisSerializer();Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =new Jackson2JsonRedisSerializer(Object.class);ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);jackson2JsonRedisSerializer.setObjectMapper(om);template.setConnectionFactory(factory);// key 序列化方式template.setKeySerializer(redisSerializer);// value 序列化template.setValueSerializer(jackson2JsonRedisSerializer);// value hashmap 序列化template.setHashValueSerializer(jackson2JsonRedisSerializer);return template;}@Beanpublic CacheManager cacheManager(RedisConnectionFactory factory) {RedisSerializer<String> redisSerializer =new StringRedisSerializer();Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = newJackson2JsonRedisSerializer(Object.class);// 解决查询缓存转换异常的问题ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);jackson2JsonRedisSerializer.setObjectMapper(om);// 配置序列化(解决乱码的问题),过期时间 600 秒RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(600)).serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)).disableCachingNullValues();RedisCacheManager cacheManager = RedisCacheManager.builder(factory).cacheDefaults(config).build();return cacheManager;}
}

image-20240429213253810

2.测试
1.编写测试的Controller
package com.sun.redis.controller;import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;/*** Description:** @Author sun* @Create 2024/4/29 21:36* @Version 1.0*/
@RestController
@RequestMapping("/redisTest")
public class TestController {@Resourceprivate RedisTemplate<String, Object> redisTemplate;@RequestMapping("/set")public String set() {redisTemplate.opsForValue().set("name", "孙显圣");return redisTemplate.opsForValue().get("name").toString();}
}
2.编写主启动类
package com.sun.redis;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/*** Description:** @Author sun* @Create 2024/4/29 21:39* @Version 1.0*/
@SpringBootApplication
public class RedisApplication {public static void main(String[] args) {SpringApplication.run(RedisApplication.class, args);}
}
3.启动测试 localhost:8080/redisTest/set

image-20240429214257425

image-20240429214242423

3.对list进行操作
1.代码
    @RequestMapping("/list")public String list() {// 清除一下库redisTemplate.delete("key");// 批量添加redisTemplate.opsForList().leftPushAll("key", "v1", "v2", "v3");// 遍历输出List<Object> range = redisTemplate.opsForList().range("key", 0, -1);return range.toString();}
2.结果

image-20240430084953906

4.注意事项
1.先看报错是无法识别的token

image-20240430085702856

2.如果使用redisTemplate进行set会先序列化,然后读取的时候也会反序列化,但是直接在客户端set不会进行序列化,所以在使用redisTemplate进行反序列化的时候就会出现问题
3.解决方式:都使用程序进行操作即可

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

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

相关文章

算法入门<一>:C++各种排序算法详解及示例源码

1、排序算法 排序算法&#xff08;sorting algorithm&#xff09;用于对一组数据按照特定顺序进行排列。排序算法有着广泛的应用&#xff0c;因为有序数据通常能够被更高效地查找、分析和处理。 1.1 评价维度 运行效率&#xff1a;我们期望排序算法的时间复杂度尽量低&#xf…

机械臂标准DH建模及正运动学分析(以IRB4600型工业机械臂为例)

1. 前言 对于工业机械臂而言&#xff0c;运动学是不考虑力学特性的情况下对机械臂的几何参数与其位置、速度、加速度等运动特性的关系研究。DH建模是运动学的基础&#xff0c;全称为Denavit-Hartenberg建模方法&#xff0c;是一种广泛应用于机器人运动学中的建模技术。该方法通…

05_G1垃圾收集器

G1垃圾收集器简介 垃圾优先 Garbage-First&#xff08;G1&#xff09;垃圾收集器面向多处理器机器&#xff0c;适用于大内存场景。它尝试在无需太多配置的情况下实现垃圾收集暂停时间目标&#xff0c;并同时实现高吞吐量。G1旨在通过适用于当前目标应用和环境的功能&#xff0…

5月4(信息差)

&#x1f384; HDMI ARC国产双精度浮点dsp杜比数码7.1声道解码AC3/dts/AAC环绕声光纤、同轴、USB输入解码板KC33C &#x1f30d; 国铁集团回应高铁票价将上涨 https://finance.eastmoney.com/a/202405043066422773.html ✨ 源代码管理平台GitLab发布人工智能编程助手DuoCha…

【前端开发---Vue2】史上最详细的Vue2入门教程,从基础到进阶带你彻底掌握Vue(三)

本篇重点分享常见指令修饰符、v-bind指令用于 class 类名 和 style 行内样式 动态控制、v-model在其他表单元素的使用...... 并结合具体案例来让小伙伴们掌握的更透彻&#xff01;喜欢就先关注一下吧~ 声明&#xff1a;图片资源来自于黑马程序员公开学习资料 本人在学习当中&am…

golang学习笔记(协程的基础知识)

golang的协程 协程是一种轻量级的线程&#xff0c;它可以实现并发执行的并行操作。协程是Go语言中的一个核心特性&#xff0c;它使得程序能够以并发的方式运行&#xff0c;并且非常高效。与传统的线程相比&#xff0c;协程的创建和销毁成本非常低&#xff0c;可以方便地启动大…

浏览器中不能使用ES6的扩展语法...报错

浏览器大多数已经支持ES6&#xff08;ECMAScript 2015&#xff09;的扩展语法&#xff08;...&#xff09;&#xff0c;包括Chrome、Firefox、Safari和Edge等。然而&#xff0c;如果你在某些浏览器中遇到无法使用扩展语法的问题&#xff0c;可能是由以下原因导致的&#xff1a;…

神经网络之防止过拟合

今天我们来看一下神经网络中防止模型过拟合的方法 在机器学习和深度学习中&#xff0c;过拟合是指模型在训练数据上表现得非常好&#xff0c;但在新的、未见过的数据上表现不佳的现象。这是因为模型过于复杂&#xff0c;以至于它学习了训练数据中的噪声和细节&#xff0c;而不…

一款开源高性能AI应用框架

前言 LobeChat 是一个基于 Next.js 框架构建的 AI 会话应用&#xff0c;旨在提供一个 AI 生产力平台&#xff0c;使用户能够与 AI 进行自然语言交互。 LobeChat应用架构 LobeChat 的整体架构由前端、EdgeRuntime API、Agents 市场、插件市场和独立插件组成。这些组件相互协作&a…

P8799 [蓝桥杯 2022 国 B] 齿轮

P8799 [蓝桥杯 2022 国 B] 齿轮 分析 最右边的齿轮的转速是最左边齿轮的q倍 最右边的齿轮的半径是最左边齿轮的q倍 题意即为&#xff1a;查询数组中是否存在两个数&#xff0c;其中一个是另一个的q倍 题目范围&#xff1a;查询次数q:2*10^5&#xff0c;数组范围2*10^5&…

XXL-JOB定时任务

1. xxl-job初识 1.1 xxl-job介绍 xxl-job 是大众点评大佬徐雪里开源的一款分布式任务调度框架&#xff0c;具有简单易用、轻量级、可扩展的特点。相比于Spring Task, Quartz&#xff0c;xxl-job有记录执行日志和运行大盘&#xff0c;方便开发人员和运维人员更好的管理任务。 …

如何进行面向对象分析、面向对象设计和面向对象编程

目录 1.引言 2.案例介绍和难点剖析 3.如何进行面向对象分析 4.如何进行面向对象设计 5.如何进行面向对象编程 6.总结 1.引言 面向对象分析(OOA)、面向对象设计(00D)和面向对象编程(OOP)是面向对象开发的3个主要环节。 在以往的工作中&#xff0c;作者发现&#xff0c;很多…

【JavaEE 初阶(一)】初识线程

❣博主主页: 33的博客❣ ▶️文章专栏分类:JavaEE◀️ &#x1f69a;我的代码仓库: 33的代码仓库&#x1f69a; &#x1faf5;&#x1faf5;&#x1faf5;关注我带你了解更多线程知识 目录 1.前言2.进程3.线程4.线程和进程的区别5.Thread创建线程5.1继承Thread创建线程5.2实现R…

专项技能训练五《云计算网络技术与应用》实训7-2:使用OpenDaylight界面下发流表

文章目录 使用OpenDaylight的web界面下发流表1. 根据前面实训教程&#xff0c;启动并登录到opendaylight的web控制页面&#xff0c;并使用mininet2. 单击左侧的“Nodes”查看节点信息。其中尤其需要关注Node Id&#xff0c;下发流表的时候会用到Node Id&#xff0c;如下图所示。…

无穷级数错题本

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <

word中取消分页符或分段符前后的空格

在Word中&#xff0c;有时候&#xff0c;我们添加分页符后&#xff0c;从分页符后面的文字就全部掉到了下一页&#xff0c;那么如何避免呢&#xff1f; 选择word选项--高级&#xff0c;然后下滑到下面&#xff0c;将“取消分页符或分段符前后的空格”选中&#xff0c;如下图所…

解读简单的一段深度学习代码(已跑通)

最近一直想要学习深度学习的内容&#xff0c;想要复现大佬的代码&#xff0c;试了好多有的是不给数据&#xff0c;有的总是跑不通&#xff0c;这一个是已经跑通的一个代码&#xff0c;以上为证&#xff0c;学习最快的方式就是直接实战&#xff0c;大部分的内容都是比较偏向于理…

机器学习笔记导航(吴恩达版)

01.机器学习笔记01&#xff1a;机器学习前置概念导入、线性回归、梯度下降算法 02.机器学习笔记02&#xff1a;多元线性回归、多元梯度下降算法、特征缩放、均值归一化、正规方程 03.机器学习笔记03&#xff1a;octave安装、创建矩阵 04.机器学习笔记04&#xff1a;octave中移动…

LeetCode题练习与总结:分隔链表--86

一、题目描述 给你一个链表的头节点 head 和一个特定值 x &#xff0c;请你对链表进行分隔&#xff0c;使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。 你应当 保留 两个分区中每个节点的初始相对位置。 示例 1&#xff1a; 输入&#xff1a;head [1,4,3,2,5,2]…

MyScaleDB:SQL+向量驱动大模型和大数据新范式

大模型和 AI 数据库双剑合璧&#xff0c;成为大模型降本增效&#xff0c;大数据真正智能的制胜法宝。 大模型&#xff08;LLM&#xff09;的浪潮已经涌动一年多了&#xff0c;尤其是以 GPT-4、Gemini-1.5、Claude-3 等为代表的模型你方唱罢我登场&#xff0c;成为当之无愧的风口…