Spring boot 中使用 Redis 信息

文章目录

        • 添加依赖:
        • 配置 Redis:
        • 配置 Jackson2JsonRedisSerializer 进行对象的序列化
        • 使用 RedisTemplate:
添加依赖:

在 pom.xml 文件中添加 Redis 和 Spring Data Redis 的依赖。 Spring boot 集成 redis 的使用, 无需版本号即可直接使用,还有相关配置信息可以直接通过 yml 文件去配置

<dependencies>
    <!-- Spring Boot Starter Data Redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>
配置 Redis:

在 application.properties 或 application.yml 文件中配置 Redis 的连接信息。

java 复制代码
redis: 
	port: 6380
	host: 127.0.0.1
配置 Jackson2JsonRedisSerializer 进行对象的序列化

要在 Spring Boot 项目中配置 Redis 的序列化,你需要自定义 RedisTemplate 的序列化策略。Spring Data Redis 默认使用 JdkSerializationRedisSerializer 来序列化和反序列化对象,但这可能导致较大的内存占用。通常推荐使用 Jackson2JsonRedisSerializer 或 OxmSerializer(如果使用 XML)来进行更高效的序列化。

java 复制代码
package org.gateway.config.redis;

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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 使用 Jackson2JsonRedisSerializer 替换默认的序列化方式
        Jackson2JsonRedisSerializer<Object> jacksonSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSerializer.setObjectMapper(om);

        template.setValueSerializer(jacksonSerializer);
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();

        return template;
    }
}
使用 RedisTemplate:

RedisTemplate 是 Spring Data Redis 提供的一个高级抽象层,用于简化 Redis 的操作。它封装了对 Redis 的基本操作,如设置和获取值、执行列表操作等,并且可以很容易地扩展到更复杂的功能。RedisTemplate 支持多种序列化策略,可以自定义序列化方式以满足特定的应用需求。

我们使用 RedisTemplate 封装一个 RedisUtil 便于使用

java 复制代码
package org.gateway.utils.redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class RedisUtil {

    private final RedisTemplate<String, Object> redisTemplate;
    private final ObjectMapper objectMapper;

    // String Operations

    public void setString(String key, String value) {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        ops.set(key, value);
    }

    public String getString(String key) {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        return (String) ops.get(key);
    }

    public void setStringWithExpiry(String key, String value, long timeout, TimeUnit unit) {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        ops.set(key, value, timeout, unit);
    }

    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    public void deleteKey(String key) {
        redisTemplate.delete(key);
    }

    // List Operations

    public void leftPush(String key, Object value) {
        ListOperations<String, Object> ops = redisTemplate.opsForList();
        ops.leftPush(key, value);
    }

    public void rightPush(String key, Object value) {
        ListOperations<String, Object> ops = redisTemplate.opsForList();
        ops.rightPush(key, value);
    }

    public List<Object> range(String key, long start, long end) {
        ListOperations<String, Object> ops = redisTemplate.opsForList();
        return ops.range(key, start, end);
    }

    public Long listSize(String key) {
        ListOperations<String, Object> ops = redisTemplate.opsForList();
        return ops.size(key);
    }

    // Hash Operations

    public void putInHash(String key, String field, Object value) {
        HashOperations<String, String, Object> ops = redisTemplate.opsForHash();
        ops.put(key, field, value);
    }

    public Object getValueFromHash(String key, String field) {
        HashOperations<String, String, Object> ops = redisTemplate.opsForHash();
        return ops.get(key, field);
    }

    public Map<String, Object> getHash(String key) {
        HashOperations<String, String, Object> ops = redisTemplate.opsForHash();
        return ops.entries(key);
    }

    public Long hashSize(String key) {
        HashOperations<String, String, Object> ops = redisTemplate.opsForHash();
        return ops.size(key);
    }

    // Set Operations

    public void addSet(String key, Object member) {
        SetOperations<String, Object> ops = redisTemplate.opsForSet();
        ops.add(key, member);
    }

    public Set<Object> membersOfSet(String key) {
        SetOperations<String, Object> ops = redisTemplate.opsForSet();
        return ops.members(key);
    }

    public Long setSize(String key) {
        SetOperations<String, Object> ops = redisTemplate.opsForSet();
        return ops.size(key);
    }

    // Sorted Set Operations

    public void addSortedSet(String key, Object member, double score) {
        ZSetOperations<String, Object> ops = redisTemplate.opsForZSet();
        ops.add(key, member, score);
    }

    public Set<Object> rangeByScore(String key, double min, double max) {
        ZSetOperations<String, Object> ops = redisTemplate.opsForZSet();
        return ops.rangeByScore(key, min, max);
    }

    public Long sortedSetSize(String key) {
        ZSetOperations<String, Object> ops = redisTemplate.opsForZSet();
        return ops.zCard(key);
    }

    // Key Operations

    public void expire(String key, long timeout, TimeUnit unit) {
        redisTemplate.expire(key, timeout, unit);
    }

    public Boolean exists(String key) {
        return redisTemplate.hasKey(key);
    }

    public void deleteKeys(Collection<String> keys) {
        redisTemplate.delete(keys);
    }

    public void setObject(String key, Object object) {
        try {
            String serializedObject = objectMapper.writeValueAsString(object);
            redisTemplate.opsForValue().set(key, serializedObject);
        } catch (IOException e) {
            throw new RuntimeException("Failed to serialize object", e);
        }
    }

    public <T> T getObject(String key, Class<T> clazz) {
        String serializedObject = (String) redisTemplate.opsForValue().get(key);
        if (serializedObject == null) {
            return null;
        }
        try {
            return objectMapper.readValue(serializedObject, clazz);
        } catch (IOException e) {
            throw new RuntimeException("Failed to deserialize object", e);
        }
    }
}
相关推荐
Dlwyz1 小时前
问题: redis-高并发场景下如何保证缓存数据与数据库的最终一致性
数据库·redis·缓存
飞升不如收破烂~2 小时前
redis的List底层数据结构 分别什么时候使用双向链表(Doubly Linked List)和压缩列表(ZipList)
redis
潜洋3 小时前
Spring Boot教程之五:在 IntelliJ IDEA 中运行第一个 Spring Boot 应用程序
java·spring boot·后端
灯雾️4 小时前
Spring Boot、Spring MVC和Spring间的区别
spring boot
吴半杯4 小时前
Redis-monitor安装与配置
数据库·redis·缓存
supercool74 小时前
SpringBoot(9)-Dubbo+Zookeeper
spring boot·dubbo·java-zookeeper
没有黑科技5 小时前
基于web的音乐网站(Java+SpringBoot+Mysql)
java·前端·spring boot
计算机毕设孵化场5 小时前
计算机毕设-基于springboot的多彩吉安红色旅游网站的设计与实现(附源码+lw+ppt+开题报告)
vue.js·spring boot·后端·计算机外设·课程设计·计算机毕设论文·多彩吉安红色旅游网站
战神刘玉栋5 小时前
《SpringBoot、Vue 组装exe与套壳保姆级教学》
vue.js·spring boot·后端
会code的厨子5 小时前
Redis缓存高可用集群
redis·缓存