当前位置: 首页 > news >正文

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;
}

运行结果:

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

相关文章:

  • 超分辨率重构论文集合
  • [网络]抓包工具介绍 tcpdump
  • xtu oj 六边形
  • flume系列之:flume jmx页面导出flume、java进程等全部指标
  • 深入理解网络通信: 长连接、短连接与WebSocket
  • 小米2025届软件开发工程师(C/C++/Java)(编程题AK)
  • OpenCV-指纹识别
  • 足球青训俱乐部管理:Spring Boot技术驱动
  • Prompt技巧总结和示例分享
  • mysql学习教程,从入门到精通,SQL 表、列别名(Aliases)(30)
  • 使用 Docker 构建 LLaMA-Factory 环境
  • windows C++-UWP 应用中使用 HttpRequest 类
  • 微软开源项目 Detours 详细介绍与使用实例分享
  • JetLinks物联网平台微服务化系列文章介绍
  • linux 目录文件夹操作
  • 《Java8实战》-第四章读书笔记(引入流Stream)
  • CSS相对定位
  • extract-text-webpack-plugin用法
  • Facebook AccountKit 接入的坑点
  • Github访问慢解决办法
  • java小心机(3)| 浅析finalize()
  • Laravel深入学习6 - 应用体系结构:解耦事件处理器
  • PV统计优化设计
  • Sequelize 中文文档 v4 - Getting started - 入门
  • VuePress 静态网站生成
  • 案例分享〡三拾众筹持续交付开发流程支撑创新业务
  • 高程读书笔记 第六章 面向对象程序设计
  • 如何将自己的网站分享到QQ空间,微信,微博等等
  • 入手阿里云新服务器的部署NODE
  • 3月27日云栖精选夜读 | 从 “城市大脑”实践,瞭望未来城市源起 ...
  • raise 与 raise ... from 的区别
  • ​​​【收录 Hello 算法】9.4 小结
  • ​无人机石油管道巡检方案新亮点:灵活准确又高效
  • ‌移动管家手机智能控制汽车系统
  • (20)目标检测算法之YOLOv5计算预选框、详解anchor计算
  • (2024)docker-compose实战 (8)部署LAMP项目(最终版)
  • (3)医疗图像处理:MRI磁共振成像-快速采集--(杨正汉)
  • (Git) gitignore基础使用
  • (八)Spring源码解析:Spring MVC
  • (附源码)基于ssm的模具配件账单管理系统 毕业设计 081848
  • (自用)learnOpenGL学习总结-高级OpenGL-抗锯齿
  • .jks文件(JAVA KeyStore)
  • .NET Core、DNX、DNU、DNVM、MVC6学习资料
  • .Net Core/.Net6/.Net8 ,启动配置/Program.cs 配置
  • .Net Core和.Net Standard直观理解
  • .NET Framework .NET Core与 .NET 的区别
  • .net refrector
  • .NET/C# 异常处理:写一个空的 try 块代码,而把重要代码写到 finally 中(Constrained Execution Regions)
  • .net的socket示例
  • .Net下的签名与混淆
  • .NET中使用Redis (二)
  • :class的用法及应用
  • ??eclipse的安装配置问题!??
  • @converter 只能用mysql吗_python-MySQLConverter对象没有mysql-connector属性’...
  • @Pointcut 使用