springboot整合redis

397 阅读7分钟
、概念:SpringBoot 整合 Redis
2、背景
Redis 的数据库的整合在 java 里面提供的官方工具包:jedis,所以即便你现在使用的是 SpringBoot,那么也继续使用此开发包。
2.1、RedisTemplate 模版操作
在 Spring 支持的 Redis 操作之中提供有一个 RedisTemplate 处理程序类,利用这个类可以非常方便的实现 Redis 的各种基本数 据操作。
1、 修改项目中的 pom.xml 配置文件,追加 redis 的依赖引用:
[XML]
纯文本查看
复制代码
1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、 如果要想使用 Redis 操作,则一定要修改 application.yml 配置文件,在这个配置文件之中要进行 Redis 的各种连接配置处理;
[XML]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
spring:
redis:
host: 192.168.68.166
port: 6379
password: studyjava
timeout: 1000
database: 0
pool:
max-active: 10
max-idle: 8
min-idle: 2
max-wait: 100
3、 下面就可以通过程序来利用 RedisTemplate 模版进行数据处理了,因为以上的配置一旦完成之后会在 Spring 内部帮助用户直接 获得一个 RedisTemplate 模版处理对象,为了简单,直接建立一个测试类完成:
[Java]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
package cn.study.microboot;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@SpringBootTest(classes = StartSpringBootMain.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class TestRedis {
@Resource
private RedisTemplate<String, String> redisTemplate;
@Test
public void testSet() {
this.redisTemplate.opsForValue().set("study", "java");
System.out.println(this.redisTemplate.opsForValue().get("study"));
}
}
则此时就可以利用 Redis 实现在 SpringBoot 中的数据存储操作了。
2.2、Redis 对象序列化操作
虽然以上的代码实现了 Redis 基础的数据操作,但是遗憾的是在 Java 开发领域内必须要考虑一个实际的问题,那么就是对象 的序列化保存问题,毕竟 Redis 数据库的读写速度是非常快的,但是如果不能够进行对象的存储,这样的存储意义就不大了,这样 就需要准备一个对象的序列化处理程序类,通过对象的形式进行数据的存储。
1、 如果要想进行 Redis 对象序列化操作则一定要首先准备一个序列化处理程序类,这个程序类有实现要求:
[Java]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package cn.study.microboot.util.redis;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
// 此时定义的序列化操作表示可以序列化所有类的对象,当然,这个对象所在的类一定要实现序列化接口
public class RedisObjectSerializer implements RedisSerializer<Object> {
// 为了方便进行对象与字节数组的转换,所以应该首先准备出两个转换器
private Converter<Object, byte[]> serializingConverter = new SerializingConverter();
private Converter<byte[], Object> deserializingConverter = new DeserializingConverter();
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; // 做一个空数组,不是null
@Override
public byte[] serialize(Object obj) throws SerializationException {
if (obj == null) { // 这个时候没有要序列化的对象出现,所以返回的字节数组应该就是一个空数组
return EMPTY_BYTE_ARRAY ;
}
return this.serializingConverter.convert(obj); // 将对象变为字节数组
}
@Override
public Object deserialize(byte[] data) throws SerializationException {
if (data == null || data.length == 0) { // 此时没有对象的内容信息
return null ;
}
return this.deserializingConverter.convert(data);
}
}
2、 此时如果要想让 RedisTemplate 操作模版知道有这样一个序列化程序类存在,那么就不能够采用 RedisTemplate 默认配置形式, 需要准备一个单独的配置类进行处理:
[Java]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
package cn.study.microboot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import cn.study.microboot.util.redis.RedisObjectSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> getRedisTemplate(
RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(new StringRedisSerializer()); // key的序列化类型
redisTemplate.setValueSerializer(new RedisObjectSerializer()); // value的序列化类型
return redisTemplate;
}
}
3、 进行程序的测试使用:
[Java]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package cn.study.microboot.vo;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Member implements Serializable {
private String mid;
private Integer age;
public String getMid() {
return mid;
}
public void setMid(String mid) {
this.mid = mid;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Member [mid=" + mid + ", age=" + age + "]";
}
}
[Java]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package cn.study.microboot;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import cn.mldn.microboot.vo.Member;
@SpringBootTest(classes = StartSpringBootMain.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class TestRedis {
@Resource
private RedisTemplate<String, Object> redisTemplate;
@Test
public void testGet() {
System.out.println(this.redisTemplate.opsForValue().get("study"));
}
@Test
public void testSet() {
Member vo = new Member() ;
vo.setMid("studyjava");
vo.setAge(19);
this.redisTemplate.opsForValue().set("study", vo);;
}
}
此时可以进行对象的序列化保存处理, 这样整体的数据存储的手段可以更加的丰富。
2.3、配置多个 RedisTemplate
由于在项目的实际开发过程之中 Redis 的使用会非常的频繁, 那么就有可能出现这样一种问题:现在的项目里面要求连接两 个 Redis 数据库。SpringBoot 里面针对于 Redis 的连接配置本质上只提供有一个连接配置项,那么如果你真的需要进行更多的 Redis 的连接配置,那么就需要自己来进行 Redis 的创建管理了。
1、 以非正规的形式修改 application.yml 配置文件:
[XML]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
spring:
redis:
host: 192.168.68.166
port: 6379
password: studyjava
timeout: 1000
database: 0
pool:
max-active: 10
max-idle: 8
min-idle: 2
max-wait: 100
redis-two:
host: 192.168.68.166
port: 6380
password: studyjava
timeout: 1000
database: 0
pool:
max-active: 10
max-idle: 8
min-idle: 2
max-wait: 100
2、 建立一个 RedisTwoConfig 的程序配置类,进行第二个 Redis 连接的配置处理:
[Java]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package cn.study.microboot.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import cn.study.microboot.util.redis.RedisObjectSerializer;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
public class RedisTwoConfig {
public RedisConnectionFactory getRedisConnectionFactory(String hostName,
String password, int port, int maxActive, int maxIdle, int minIdle,
long maxWait, int database) { // 是负责建立Factory的连接工厂类
JedisConnectionFactory jedisFactory = new JedisConnectionFactory();
jedisFactory.setHostName(hostName);
jedisFactory.setPort(port);
jedisFactory.setPassword(password);
jedisFactory.setDatabase(database);
JedisPoolConfig poolConfig = new JedisPoolConfig(); // 进行连接池配置
poolConfig.setMaxTotal(maxActive);
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
poolConfig.setMaxWaitMillis(maxWait);
jedisFactory.setPoolConfig(poolConfig);
jedisFactory.afterPropertiesSet(); // 初始化连接池配置
return jedisFactory;
}
@Bean("redisTwo")
public RedisTemplate<String, Object> getRedisTemplate(
@Value("${spring.redis-two.host}") String hostName,
@Value("${spring.redis-two.password}") String password,
@Value("${spring.redis-two.port}") int port,
@Value("${spring.redis-two.database}") int database,
@Value("${spring.redis-two.pool.max-active}") int maxActive,
@Value("${spring.redis-two.pool.max-idle}") int maxIdle,
@Value("${spring.redis-two.pool.min-idle}") int minIdle,
@Value("${spring.redis-two.pool.max-wait}") long maxWait) {
RedisConnectionFactory factory = this.getRedisConnectionFactory(
hostName, password, port, maxActive, maxIdle, minIdle, maxWait,
database); // 建立Redis的连接
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(new StringRedisSerializer()); // key的序列化类型
redisTemplate.setValueSerializer(new RedisObjectSerializer()); // value的序列化类型
return redisTemplate;
}
}
3、 编写测试程序类:
[Java]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package cn.study.microboot;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import cn.study.microboot.vo.Member;
@SpringBootTest(classes = StartSpringBootMain.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class TestRedisTwo {
@Resource(name="redisTwo")
private RedisTemplate<String, Object> redisTemplate;
@Test
public void testGet() {
System.out.println(this.redisTemplate.opsForValue().get("study"));
}
@Test
public void testSet() {
Member vo = new Member() ;
vo.setMid("studyjava");
vo.setAge(19);
this.redisTemplate.opsForValue().set("study", vo);;
}
}
在实际的工作之中由于 Redis 数据库的使用相当频繁,所以有很大的可能性是一个项目里面需要连接不同的 Redis 数据库。
3、总结
Redis 是一个重要的数据库产品,实际开发之中会利用 Redis 实现高并发的信息存储,所以多个 Redis 数据库的使用是一种常 见形式。
本文引自博客:https://www.cnblogs.com/leeSmall/p/8728231.html