【springboot进阶】springboot集成fastjson(三)配置redis使用fastJson进行序列化

目录

一、引入依赖

二、添加redis连接配置

三、新建RedisConfig类配置

四、测试

 五、踩过的坑

数字型的保存

对象的保存 


上一章节,我们说到fastjson的自定义序列化和反序列化,这章节,我们看看如何配置redis使用fastjson进行序列化。

一、引入依赖

默认使用的redis连接为方式为lettuce

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

二、添加redis连接配置

在application.yml文件中,添加redis配置

#redis配置
spring:
  redis:
    host: 127.0.0.1
    password:
    port: 6379
    database: 3
    # 连接超时时间(毫秒)
    timeout: 10s
    client-type: lettuce
    lettuce:
      pool:
        # 连接池最大连接数(使用负值表示没有限制) 默认 8
        max-active: 1000
        # 连接池中的最大空闲连接 默认 8
        max-idle: 300
        # 连接池中的最小空闲连接 默认 0
        min-idle: 3
        # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
        max-wait: 1s

三、新建RedisConfig类配置

@Configuration
public class FastjsonRedisConfig {

    /**
     * 自定义redisTemplate配置
     *
     * 使用的序列化方式
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //key值使用spring默认的StringRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //value值使用fastjson的GenericFastJsonRedisSerializer
        GenericFastJsonRedisSerializer fastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);
        //以下是hash序列化的配置
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);

        return redisTemplate;
    }

}

四、测试

编写测试demo

@SpringBootTest
class SpringbootFastjsonApplicationTests {

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @Test
    void contextLoads() {

        redisTemplate.opsForValue().set("fastjson_key", "a1b2c3", Duration.ofMinutes(5));

        Object object = redisTemplate.opsForValue().get("fastjson_key");
        System.out.println(object);
    }

}

从调试窗口可以看到,redis连接池和redis连接配置信息,都是我们上面设置的。

 运行后,我们看一下redis保存的信息是否存在。

 可以看到在3库里面,保存着我们刚才设置的值。

这里看出,使用fastjson保存的字符串,会多出两个引号,这是区分字符和数字的标志。

 五、踩过的坑

使用fastJson进行序列化时,有一些坑是需要注意的。

数字型的保存

如果我们使用的是字符串来保存一个数字,那么我们就不能够在获取值的时候强制转化为数字型,否则会报错。

redisTemplate.opsForValue().set("fastjson_key", "123", Duration.ofMinutes(5));

Integer object = (Integer)redisTemplate.opsForValue().get("fastjson_key");
System.out.println(object);

如下图报错信息

这里有个坑点就是,保存的时候用了字符串,但是取的时候印象中记得是一个数字,所以就理想当然的用数字型来强制转换,就会报错。redis中也是用的双引号标志,这是一个字符串,所以fastjson取值的时候也当作是一个字符串来处理。

 我们在看看,如果我们存的是一个数字型,是怎么样的。

可以看到,外层没有了双引号,fastjson也能识别出一个数字型,所以这次强转是没有报错了。

对象的保存 

建议保存对象的时候,能够先序列化为json字符串再保存,然后在获取的时候,再从字符串转为对应的对象。

如果我们直接保存对象到redis,代码如下。

FastjsonDemoRequest fastjsonDemoRequest = new FastjsonDemoRequest();
fastjsonDemoRequest.setUserName("张三");
fastjsonDemoRequest.setAge(18);
fastjsonDemoRequest.setMoney("1.8");

redisTemplate.opsForValue().set("fastjson_key", fastjsonDemoRequest, Duration.ofMinutes(5));

FastjsonDemoRequest object = (FastjsonDemoRequest)redisTemplate.opsForValue().get("fastjson_key");
System.out.println(object);

此时的redis保存的值,如下图,这里多了一个"@type",值为这个类的class包路径。

这里会有什么问题呢?如果在其他的业务系统中,也要读取这个值,因为不同的系统间,包路径命名等不同,就会导致取值的时候会报错,如下图。

FastjsonDemoRequest fastjsonDemoRequest = new FastjsonDemoRequest();
fastjsonDemoRequest.setUserName("张三");
fastjsonDemoRequest.setAge(18);
fastjsonDemoRequest.setMoney("1.8");

redisTemplate.opsForValue().set("fastjson_key", fastjsonDemoRequest, Duration.ofMinutes(5));

org.liurb.springboot.fastjson.redis.FastjsonDemoRequest object = (org.liurb.springboot.fastjson.redis.FastjsonDemoRequest)redisTemplate.opsForValue().get("fastjson_key");
System.out.println(object);

报错信息,如下图

如果我们先序列化为一个json字符串,代码如下

FastjsonDemoRequest fastjsonDemoRequest = new FastjsonDemoRequest();
fastjsonDemoRequest.setUserName("张三");
fastjsonDemoRequest.setAge(18);
fastjsonDemoRequest.setMoney("1.8");

redisTemplate.opsForValue().set("fastjson_key", JSON.toJSONString(fastjsonDemoRequest), Duration.ofMinutes(5));

String str = (String)redisTemplate.opsForValue().get("fastjson_key");

org.liurb.springboot.fastjson.redis.FastjsonDemoRequest object = JSON.parseObject(str, org.liurb.springboot.fastjson.redis.FastjsonDemoRequest.class);

System.out.println(object);

这样,我们就不需要担心因为跨业务系统导致包路径不相同,或者我们重命名为另外一个类的名字,都可以正常获取到redis的值,只要字段名字相同就行了。

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
首先,在Spring Boot项目中添加RedisFastjson的依赖: ```xml <!-- Redis依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- Fastjson依赖 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.73</version> </dependency> ``` 接着,在application.yml中配置Redis连接信息: ```yaml spring: redis: host: localhost port: 6379 password: database: 0 ``` 然后,我们可以创建一个RedisUtil类来操作Redis,示例如下: ```java import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; @Component public class RedisUtil { @Autowired private RedisTemplate<String, Object> redisTemplate; /** * 添加缓存 * @param key * @param value * @param expireTime */ public void set(String key, Object value, long expireTime) { if (value instanceof String) { redisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS); } else { redisTemplate.opsForValue().set(key, JSON.toJSONString(value, SerializerFeature.WriteClassName), expireTime, TimeUnit.SECONDS); } } /** * 获取缓存 * @param key * @param clazz * @param <T> * @return */ public <T> T get(String key, Class<T> clazz) { Object value = redisTemplate.opsForValue().get(key); return value == null ? null : JSON.parseObject(value.toString(), clazz); } /** * 删除缓存 * @param key */ public void delete(String key) { redisTemplate.delete(key); } } ``` 在上面的代码中,我们使用Fastjson对对象进行序列化和反序列化,并且在set方法中判断了value的类型,如果是String类型,则直接存储,否则使用Fastjson将对象序列化后再存储。在get方法中,我们先获取缓存的值,然后判断是否为null,如果不为null,则使用Fastjson将值反序列化成指定的class类型。 最后,在需要使用Redis的地方,我们可以注入RedisUtil,然后调用它的方法即可: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @Autowired private RedisUtil redisUtil; @GetMapping("/test") public String test() { String key = "test"; String value = "hello world"; redisUtil.set(key, value, 60); String result = redisUtil.get(key, String.class); return result; } } ``` 以上就是在Spring Boot项目中集成Redis使用Fastjson进行序列化的示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

reui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值