目录
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;
}
运行结果:
从运行结果可以看出,学生对象已经被加入缓存并且可以从缓存中读取出来,符合预期