SpringBoot集成Redis,使用fastjson存储json格式数据

添加依赖

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.78</version>
		</dependency>

添加配置

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制) 默认为8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认为-1
spring.redis.lettuce.pool.max-wait=-1ms
# 连接池中的最大空闲连接 默认为8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认为 0
spring.redis.lettuce.pool.min-idle=0

自定义 RedisTemplate

package com.example.demo.redis;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.data.redis.connection.DefaultStringRedisConnection;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * @author  guochao
 * @date  2021/12/13 23:15
 * @version 1.0
 */
public class ObjectRedisTemplate extends RedisTemplate<String, Object> {

	public ObjectRedisTemplate() {
		setKeySerializer(RedisSerializer.string());
		setValueSerializer(new GenericFastJsonRedisSerializer());
		setHashKeySerializer(RedisSerializer.string());
		setHashValueSerializer(new GenericFastJsonRedisSerializer());
	}

	public ObjectRedisTemplate(RedisConnectionFactory connectionFactory) {
		this();
		setConnectionFactory(connectionFactory);
		afterPropertiesSet();
	}

	protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
		return new DefaultStringRedisConnection(connection);
	}
}

package com.example.demo.redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;

/**
 * @author  guochao
 * @date  2021/12/13 23:16
 * @version 1.0
 */
@Configuration
public class RedisConfig {
    @Bean
    public ObjectRedisTemplate objectRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        return new ObjectRedisTemplate(redisConnectionFactory);
    }
}

定义测试实体类

package com.example.demo.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author guochao
 * @version 1.0
 * @date 2021/12/13 23:18
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer id;
    private String name;
    private Integer age;
}

定义测试类

package com.example.demo;

import com.example.demo.entity.User;
import com.example.demo.redis.ObjectRedisTemplate;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

@SpringBootTest
@Slf4j
public class RedisTest {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ObjectRedisTemplate objectRedisTemplate;

    /**
     * 对象存储实例
     */
    @Test
    public void testObject() {
        String key = "user:1";
        objectRedisTemplate.opsForValue().set(key, new User(1, "郭碧婷", 20));
        User user = (User) objectRedisTemplate.opsForValue().get(key);
        log.info("uesr: " + user);
    }

    /**
     * 字符串存储实例
     */
    @Test
    public void testString() {
        stringRedisTemplate.opsForValue().set("key", "唐嫣");
        String key = stringRedisTemplate.opsForValue().get("key");
        log.info(key);
    }

    /**
     * 测试时间存储实例
     */
    @Test
    public void testTime() {
        //存储20秒
        stringRedisTemplate.opsForValue().set("key", "鱼闪闪", 20, TimeUnit.SECONDS);
        String key = stringRedisTemplate.opsForValue().get("key");
        log.info(key);
    }

    /**
     * 测试时间存储实例2
     */
    @Test
    public void testTime2() {
        //存储20秒
        stringRedisTemplate.opsForValue().set("key", "鱼闪闪", Duration.ofSeconds(20));
        String key = stringRedisTemplate.opsForValue().get("key");
        log.info(key);
    }
}

源码地址

https://github.com/ofoo/my-spring-boot/tree/master/spring-boot-redis

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值