SpringBoot-Redis

redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。
这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。
与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。
--摘自百度百科

使用Redis非常简单,首先要引入依赖。

开始撸代码,目录结构:

引入edis依赖spring-boot-starter-data-redis

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 4   <modelVersion>4.0.0</modelVersion>
 5   <parent>
 6     <groupId>org.springframework.boot</groupId>
 7     <artifactId>spring-boot-starter-parent</artifactId>
 8     <version>2.0.6.RELEASE</version>
 9     <relativePath/> <!-- lookup parent from repository -->
10   </parent>
11 
12   <groupId>com.mike.study</groupId>
13   <artifactId>springboot-redis</artifactId>
14   <version>0.0.1-SNAPSHOT</version>
15   <name>springboot-redis</name>
16   <description>Demo project for Spring Boot</description>
17 
18   <properties>
19     <java.version>1.8</java.version>
20   </properties>
21   <dependencies>
22     <dependency>
23       <groupId>org.springframework.boot</groupId>
24       <artifactId>spring-boot-starter-data-redis</artifactId>
25     </dependency>
26     <dependency>
27       <groupId>org.springframework.boot</groupId>
28       <artifactId>spring-boot-starter-web</artifactId>
29     </dependency>
30 
31     <dependency>
32       <groupId>com.alibaba</groupId>
33       <artifactId>fastjson</artifactId>
34       <version>1.2.8</version>
35     </dependency>
36 
37     <dependency>
38       <groupId>org.springframework.boot</groupId>
39       <artifactId>spring-boot-starter-test</artifactId>
40       <scope>test</scope>
41     </dependency>
42     <dependency>
43       <groupId>io.projectreactor</groupId>
44       <artifactId>reactor-test</artifactId>
45       <scope>test</scope>
46     </dependency>
47   </dependencies>
48 
49   <build>
50     <plugins>
51       <plugin>
52         <groupId>org.springframework.boot</groupId>
53         <artifactId>spring-boot-maven-plugin</artifactId>
54       </plugin>
55     </plugins>
56   </build>
57 
58 </project>

在application.yml配置redis。安装教程自行网上找资料安装,这里不展开介绍

1 spring:
2   data:
3     redis:
4       host: 127.0.0.1
5       port: 6379

简单创建一个订单对象,用来测试redis存储。

 1 /**
 2  * @Classname OrderInfo
 3  * @Created by Michael
 4  * @Date 2023/5/25
 5  * @Description 订单信息类
 6  */
 7 public class OrderInfo {
 8   private long orderID;
 9   private String orderNo;
10 
11   public long getOrderID() {
12     return orderID;
13   }
14 
15   public void setOrderID(long orderID) {
16     this.orderID = orderID;
17   }
18 
19   public String getOrderNo() {
20     return orderNo;
21   }
22 
23   public void setOrderNo(String orderNo) {
24     this.orderNo = orderNo;
25   }
26 }

其实到此已经可以使用redis了,但是如果往redis保存kv时,会出现一串陌生的字符串。所以要想保存对象,必须配置序列化器,可以使用框架自带的序列化器,也可以引入第三方的的序列化器,例如FastJSON的序列化器。

创建自定义的序列化器

 1 import com.alibaba.fastjson.JSON;
 2 import com.alibaba.fastjson.serializer.SerializerFeature;
 3 import org.springframework.data.redis.serializer.RedisSerializer;
 4 import org.springframework.data.redis.serializer.SerializationException;
 5 
 6 import java.nio.charset.Charset;
 7 
 8 /**
 9  * @Classname FastJsonRedisSerializer
10  * @Created by Michael
11  * @Date 2023/5/25
12  * @Description 自定义FastJSON的serializer
13  */
14 public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
15 
16   public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
17   private Class<T> clazz;
18 
19   public FastJsonRedisSerializer(Class<T> clazz) {
20     super();
21     this.clazz = clazz;
22   }
23 
24   @Override
25   public byte[] serialize(T t) throws SerializationException {
26     if (null == t) {
27       return new byte[0];
28     }
29     return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
30   }
31 
32   @Override
33   public T deserialize(byte[] bytes) throws SerializationException {
34     if (null == bytes || bytes.length <= 0) {
35       return null;
36     }
37     String str = new String(bytes, DEFAULT_CHARSET);
38     return (T) JSON.parseObject(str, clazz);
39   }
40 }

 

创建RedisConfiguration.java,配置两个序列化器,一个springboot自带的,一个是FastJSON,使用不同的beanName(方法名).

 1 import com.mike.study.springbootredis.serializer.FastJsonRedisSerializer;
 2 import org.springframework.context.annotation.Bean;
 3 import org.springframework.context.annotation.Configuration;
 4 import org.springframework.data.redis.connection.RedisConnectionFactory;
 5 import org.springframework.data.redis.core.RedisTemplate;
 6 import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
 7 import org.springframework.data.redis.serializer.RedisSerializer;
 8 import org.springframework.data.redis.serializer.StringRedisSerializer;
 9 
10 /**
11  * @Classname RedisConfiguration
12  * @Created by Michael
13  * @Date 2023/5/25
14  * @Description Redis配置序列化器
15  */
16 @Configuration
17 public class RedisConfiguration {
18   @Bean
19   public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
20     RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
21     redisTemplate.setConnectionFactory(connectionFactory);
22     // 使用jackson2的序列对象
23     RedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
24     redisTemplate.setDefaultSerializer(genericJackson2JsonRedisSerializer);
25 
26     return redisTemplate;
27   }
28 
29   @Bean
30   public RedisTemplate<Object, Object> customRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
31       RedisTemplate<Object, Object> template = new RedisTemplate<>();
32       //使用fastjson序列化
33       FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
34       // value值的序列化采用fastJsonRedisSerializer
35       template.setValueSerializer(fastJsonRedisSerializer);
36       template.setHashValueSerializer(fastJsonRedisSerializer);
37       // key的序列化采用StringRedisSerializer
38       template.setKeySerializer(new StringRedisSerializer());
39       template.setHashKeySerializer(new StringRedisSerializer());
40       template.setConnectionFactory(redisConnectionFactory);
41       return template;
42   }
43 }

比较调用不同的序列化器redis的存储结果

 1 import com.mike.study.springbootredis.domain.OrderInfo;
 2 import org.springframework.boot.SpringApplication;
 3 import org.springframework.boot.autoconfigure.SpringBootApplication;
 4 import org.springframework.context.ConfigurableApplicationContext;
 5 import org.springframework.data.redis.core.RedisTemplate;
 6 
 7 @SpringBootApplication
 8 public class SpringbootRedisApplication {
 9 
10   public static void main(String[] args) {
11     ConfigurableApplicationContext 
12             context = SpringApplication.run(SpringbootRedisApplication.class, args);
13     OrderInfo orderInfo = new OrderInfo();
14     // 使用默认的序列化器 redisTemplate
15     RedisTemplate redisTemplate
16             = context.getBean("redisTemplate", RedisTemplate.class);
17 
18 //    redisTemplate.opsForValue().set("test", "测试");//没有定义序列化器,会出现长长的字符串
19 
20     orderInfo.setOrderID(123456L);
21     orderInfo.setOrderNo("订单号:20230525A112");
22     //使用默认序列化器
23     redisTemplate.opsForValue().set("order",orderInfo);
24 
25 
26     //使用自定义序列化器
27     RedisTemplate redisTemplate2
28             = context.getBean("customRedisTemplate", RedisTemplate.class);
29     orderInfo.setOrderID(98765L);
30     orderInfo.setOrderNo("订单号:20230525A996");
31     //使用默认序列化器
32     redisTemplate2.opsForValue().set("order2",orderInfo);
33     context.close();
34 
35 
36   }
37 
38 }

查看结果

 

 

 

 

 

对比得知,自带的序列化器生成的key是带双引号的,且保存@class信息,而使用FastJSON的序列化器的key是不带双引号,且带的是@type的信息。

 

posted @ 2023-05-26 00:10  天晴修屋顶  阅读(67)  评论(0编辑  收藏  举报