Redis介绍及整合Spring

目录

 

Redis介绍

Spring与Redis集成


Redis介绍

        Redis是内存数据库,Key-value型NOSQL数据库,项目上经常将一些不经常变化并且反复查询的数据放入Redis缓存,由于数据放在内存中,所以查询、维护的速度远远快于硬盘方式操作数据(关系型数据库)。

        Redis的数据存储在内存中,同时也会持久化到硬盘中,极端情况Redis服务器宕机时,缓存数据也可以从硬盘中恢复。

        Redis的常用配置(配置文件redis.conf)如下:

  • daemonize yes   设置 Redis 以守护进程方式运行,启动后台运行

  • port 6379 设置 Redis 监听的端口,默认为 6379

  • logfile "/var/log/redis/redis-server.log"  设置 Redis 日志文件路径

  • databases 16  设置数据库数量,默认16个数据库 (0...15)

  • dir 设置数据文件目录

  • requirepass yourpassword  设置 Redis 密码

  • tcp-keepalive 300 设置客户端空闲超时时间

        Redis操作缓存常用命令如下:

  • select 选择数据库,select 0 选择0号数据库
  • set 存放数据,命令格式为 set key value
  • get 获取数据,命令格式为 get key
  • keys 命令可以取符合规则的键值列表,通常情况可以结合*、?等选项来使用
  • exists 命令可以判断键值是否存在
  • del 命令可以删除当前数据库的指定 key

Spring与Redis集成

1、增加依赖【pom.xml】

重点依赖说明:jedis是java操作redis的客户端;spring-data-redis 是Spring和redis的集成包

    <dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.20.RELEASE</version></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-redis</artifactId><version>2.3.6.RELEASE</version></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>3.7.1</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.0</version><scope>provided</scope></dependency></dependencies>

2、Redis配置

Redis配置文件【redis_config.properties】

spring.redis.host=ip
spring.redis.port=port
spring.redis.password=password
spring.redis.database=0

Redis配置类【RedisConfig】,Spring IOC容器管理 

package com.text.config;import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
@PropertySource("classpath:redis_config.properties")
public class RedisConfig {@Value("${spring.redis.host}")private String host;@Value("${spring.redis.port}")private Integer port;@Value("${spring.redis.password}")private String password;@Value("${spring.redis.database}")private Integer database;@Beanpublic RedisConnectionFactory redisConnectionFactory() {RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();redisStandaloneConfiguration.setHostName(host);redisStandaloneConfiguration.setPort(port);redisStandaloneConfiguration.setPassword(password);redisStandaloneConfiguration.setDatabase(database);RedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration);return redisConnectionFactory;}@Beanpublic RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate redisTemplate = new RedisTemplate();redisTemplate.setConnectionFactory(redisConnectionFactory);//设置key值的序列化方式,默认是JDK的形式redisTemplate.setKeySerializer(StringRedisSerializer.UTF_8);return redisTemplate;}
}

重点代码说明: 

  • host ,port等属性值,来自于配置属性文件redis_config.properties
  • 通过配置生成了RedisConnectionFactory,IOC容器管理
  • 通过RedisConnectionFactory实例参数生成了RedisTemplate 实例,此实例对象就可以对Redis进行CRUD操作,IOC容器管理

Spring配置:此配置比较简单,只是开启了注解扫描包

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:task="http://www.springframework.org/schema/task"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/spring-task.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd"><context:component-scan base-package="com.text"/>
</beans>

3、测试类

package com.text.test;import com.text.entity.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;import javax.annotation.Resource;@Component
public class Application {@Resourceprivate RedisTemplate redisTemplate;public void testRedis() {Student s1 = new Student("1","张三",18);Student s2 = new Student("2","李四",19);Student s3 = new Student("3","王五",20);redisTemplate.opsForValue().set(s1.getId(),s1);redisTemplate.opsForValue().set(s2.getId(),s2);redisTemplate.opsForValue().set(s3.getId(),s3);Student student = (Student)redisTemplate.opsForValue().get(s3.getId());System.out.println(student);}public static void main(String[] args) throws Exception {ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");RedisTemplate redisTemplate = context.getBean("redisTemplate", RedisTemplate.class);System.out.println("redisTemplate:" + redisTemplate);Application application = context.getBean("application", Application.class);System.out.println("application:" + application);application.testRedis();}
}

重点代码说明:

  • 运行main程序后,spring容器启动,相关的对象都被实例化,包括Application,通过该实例对象注入的redisTemplate对象 set/get方法对Redis缓存进行操作。
  • Student 对象需要序列化
package com.text.entity;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.io.Serializable;@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {private String id;private String name;private int age;
}

运行结果:

从运行结果可以看出,学生对象已经被加入缓存并且可以从缓存中读取出来,符合预期

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

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

相关文章

启动服务并登录MySQL9数据库

【图书推荐】《MySQL 9从入门到性能优化&#xff08;视频教学版&#xff09;》-CSDN博客 《MySQL 9从入门到性能优化&#xff08;视频教学版&#xff09;&#xff08;数据库技术丛书&#xff09;》(王英英)【摘要 书评 试读】- 京东图书 (jd.com) Windows平台下安装与配置MyS…

解密自闭症康复方法:帮助孩子走出困境

在人生的长河中&#xff0c;每一个孩子都是家庭的希望&#xff0c;是父母心中最柔软的那一部分。然而&#xff0c;当自闭症这一沉重的阴霾笼罩在某些家庭之上时&#xff0c;那份希望似乎变得遥不可及。但请相信&#xff0c;无论前路多么艰难&#xff0c;总有一束光&#xff0c;…

Llama3.2开源:Meta发布1B和3B端侧模型、11B和90B多模态模型

最近这一两周不少互联网公司都已经开始秋招提前批面试了。 不同以往的是&#xff0c;当前职场环境已不再是那个双向奔赴时代了。求职者在变多&#xff0c;HC 在变少&#xff0c;岗位要求还更高了。 最近&#xff0c;我们又陆续整理了很多大厂的面试题&#xff0c;帮助一些球友…

用python裁切PDF文件中的图片

想把所有pdf文件的图片下边裁切掉一块&#xff0c;用Adobe Acrobat只能一页页处理&#xff0c;于是想到了用python进行批处理。 代码如下&#xff1a; """ Title: cutPdfImage Author: JackieZheng Date: 2024-09-26 20:51:24 LastEditTime: 2024-09-26 22:14…

大数据毕业设计选题推荐-民族服饰数据分析系统-Python数据可视化-Hive-Hadoop-Spark

✨作者主页&#xff1a;IT研究室✨ 个人简介&#xff1a;曾从事计算机专业培训教学&#xff0c;擅长Java、Python、微信小程序、Golang、安卓Android等项目实战。接项目定制开发、代码讲解、答辩教学、文档编写、降重等。 ☑文末获取源码☑ 精彩专栏推荐⬇⬇⬇ Java项目 Python…

栏目二:Echart绘制动态折线图+柱状图

栏目二&#xff1a;Echart绘制动态折线图柱状图 配置了一个ECharts图表&#xff0c;该图表集成了数据区域缩放、双Y轴显示及多种图表类型&#xff08;折线图、柱状图、象形柱图&#xff09;。图表通过X轴数据展示&#xff0c;支持平滑折线展示比率数据并自动添加百分比标识&…

Docker-2.如何保存数据退出

在使用Docker时&#xff0c;我们常常需要修改容器中的文件&#xff0c;并且希望在容器重启后这些修改能够得到保留。 0.简介 使用Docker时有一个需要注意的问题&#xff1a;当你修改了容器中的文件后&#xff0c;重启容器后这些修改将会被重置&#xff0c;深入研究这个问题。 …

Java类设计模式

1、单例模式 核心&#xff1a;保证一个类只有一个对象&#xff0c;并且提供一个访问该实例的全局访问点 五种单例模式&#xff1a;主要&#xff1a;饿汉式&#xff1a;线程安全&#xff0c;调用效率高&#xff0c;不能延时加载懒汉式&#xff1a;线程安全&#xff0c;调用效率…

从零开始Ubuntu24.04上Docker构建自动化部署(三)Docker安装Nginx

安装nginx sudo docker pull nginx 启动nginx 宿主机创建目录 sudo mkdir -p /home/nginx/{conf,conf.d,html,logs} 先启动nginx sudo docker run -d --name mynginx -p 80:80 nginx 宿主机上拷贝docker上nginx服务上文件到本地目录 sudo docker cp mynginx:/etc/nginx/ngin…

企业间图文档发放:如何在保障安全的同时提升效率?

不管是大型企业&#xff0c;还是小型创业公司&#xff0c;不论企业规模大小&#xff0c;每天都会有大量的图文档发放&#xff0c;对内传输协作和对外发送使用&#xff0c;数据的生产也是企业业务生产力的体现之一。 伴随着业务范围的不断扩大&#xff0c;企业与客户、合作伙伴之…

五子棋双人对战项目(2)——登录模块

目录 一、数据库模块 1、创建数据库 2、使用MyBatis连接并操作数据库 编写后端数据库代码 二、约定前后端交互接口 三、后端代码编写 文件路径如下&#xff1a; UserAPI&#xff1a; UserMapper&#xff1a; 四、前端代码 登录页面 login.html&#xff1a; 注册页面…

鸿蒙harmonyos next flutter通信之EventChannel获取ohos系统时间

建立通道 flutter代码&#xff1a; EventChannel eventChannel EventChannel("com.xmg.eventChannel"); ohos代码&#xff1a; //定义eventChannelprivate eventChannel: EventChannel | null null//定义eventSinkprivate eventSink: EventSink | null null//建…

SQL常用语法

SQL&#xff08;Structured Query Language&#xff09;是一种用于存储、操作和检索数据库中数据的标准编程语言。以下是一些常用的 SQL 语法&#xff1a; 数据库操作 创建数据库&#xff1a;CREATE DATABASE database_name;删除数据库&#xff1a;DROP DATABASE database_name…

linux dbus介绍,彻底懂linux bluez dbus

零. 前言 由于Bluez的介绍文档有限,以及对Linux 系统/驱动概念、D-Bus 通信和蓝牙协议都有要求,加上网络上其实没有一个完整的介绍Bluez系列的文档,所以不管是蓝牙初学者还是蓝牙从业人员,都有不小的难度,学习曲线也相对较陡,所以我有了这个想法,专门对Bluez做一个系统…

什么是大语言模型的上下文窗口

在大语言模型的使用中&#xff0c;“支持 32k 上下文”的意思是该模型可以处理并记住最多 32,000 个标记&#xff08;tokens&#xff09;的输入。这些标记通常是文本的最小组成部分&#xff0c;可以是一个字符、一个单词&#xff0c;或一个词组的部分。大多数自然语言处理模型并…

在 Java 中提供接口方法而不是实现接口

问题 我正在阅读有关Java中的接口的文章。其中提到我们必须实现compareTo方法才能在ArrayList容器上调用sort&#xff0c;例如Employee类应该实现 Comparable接口。 后面解释了为什么Employee类不能简单地提供compareTo方法而不实现Comparable接口&#xff1f;之所以需要接口…

ireport 5.1 中文生辟字显示不出来,生成PDF报字体找不到

ireport生成pdf里文字不显示。本文以宋体中文字不显示为例。 问题&#xff1a;由浅入深一步一步分析 问题1、预览正常&#xff0c;但生成pdf中文不显示 报告模板编辑后&#xff0c;预览正常&#xff0c;但生成pdf中文不显示。以下是试验过程&#xff1a; 先编辑好一个报告单模…

SkyWalking 告警功能

SkyWalking 告警功能是在 6.x 版本新增的,其核心由一组规则驱动,这些规则定义在config/alarm-settings.yml文件中。 告警规则 告警规则:它们定义了应该如何触发度量警报,应该考虑什么条件。Webhook(网络钩子):定义当警告触发时,哪些服务终端需要被告知。常用告警规则 …

在 Docker 版 RStudio 中安装 Seurat V4 的完整教程 (同样适用于普通R环境安装)

在单细胞RNA测序&#xff08;scRNA-seq&#xff09;数据分析领域&#xff0c;Seurat 是一个广泛使用且功能强大的R包&#xff0c;提供了丰富的数据处理和可视化工具。为了简化环境配置和依赖管理&#xff0c;使用Docker来部署RStudio并安装Seurat V4是一种高效且可重复的方法。…

华硕天选笔记本外接音箱没有声音

系列文章目录 文章目录 系列文章目录一.前言二.解决方法第一种方法第二种方法 一.前言 华硕天选笔记本外接音箱没有声音&#xff0c;在插上外接音箱时&#xff0c;系统会自动弹出下图窗口 二.解决方法 第一种方法 在我的电脑上选择 Headphone Speaker Out Headset 这三个选项…