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