当前位置: 首页 > article >正文

Spring Boot 应用程序中集成 Redis 并实现存储读取字符串或者复杂对象

步骤如下:

1. 添加依赖

确保你的 pom.xml 中包含以下依赖:

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

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

    <!-- Jackson for JSON serialization/deserialization -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>

    <!-- Lombok (可选) -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <scope>provided</scope>
    </dependency>
</dependencies>

2. 配置 Redis

在 application.properties 文件中配置 Redis 连接信息:

spring.redis.host=localhost
spring.redis.port=6379

3. 配置 RedisTemplate

创建一个配置类来配置 RedisTemplate,以便支持多种数据类型的序列化和反序列化:

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.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

@Configuration
public class RedisConfig {

    @Bean
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        //LocalDatetime序列化
        JavaTimeModule timeModule = new JavaTimeModule();
        timeModule.addDeserializer(LocalDate.class,
                new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        timeModule.addDeserializer(LocalDateTime.class,
                new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        timeModule.addSerializer(LocalDate.class,
                new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        timeModule.addSerializer(LocalDateTime.class,
                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        om.registerModule(timeModule);

        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

4. 创建 Redis 服务类

创建一个服务类来封装 Redis 操作,支持多种数据类型:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.Map;

@Service
public class RedisService {

    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public RedisService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // 存储字符串
    public void setString(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    // 获取字符串
    public String getString(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }

    // 存储对象
    public void setObject(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    // 获取对象
    public <T> T getObject(String key, Class<T> clazz) {
        return clazz.cast(redisTemplate.opsForValue().get(key));
    }

    // 存储列表
    public void setList(String key, List<Object> list) {
        redisTemplate.opsForList().rightPushAll(key, list);
    }

    // 获取列表
    public List<Object> getList(String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    // 存储集合
    public void setSet(String key, Set<Object> set) {
        redisTemplate.opsForSet().add(key, set.toArray());
    }

    // 获取集合
    public Set<Object> getSet(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    // 存储哈希表
    public void setHash(String key, Map<Object, Object> map) {
        redisTemplate.opsForHash().putAll(key, map);
    }

    // 获取哈希表
    public Map<Object, Object> getHash(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    // 删除键
    public void deleteKey(String key) {
        redisTemplate.delete(key);
    }
}

5. 创建控制器

创建一个控制器来暴露 REST API,以便客户端可以调用 Redis 操作:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.Arrays;
import java.util.HashMap;

@RestController
@RequestMapping("/api/redis")
public class RedisController {

    private final RedisService redisService;

    @Autowired
    public RedisController(RedisService redisService) {
        this.redisService = redisService;
    }

    // 设置字符串
    @PostMapping("/setString")
    public String setString(@RequestParam String key, @RequestParam String value) {
        redisService.setString(key, value);
        return "Value set successfully";
    }

    // 获取字符串
    @GetMapping("/getString")
    public String getString(@RequestParam String key) {
        return redisService.getString(key);
    }

    // 设置对象
    @PostMapping("/setObject")
    public String setObject(@RequestParam String key, @RequestBody Object value) {
        redisService.setObject(key, value);
        return "Object set successfully";
    }

    // 获取对象
    @GetMapping("/getObject")
    public Object getObject(@RequestParam String key) {
        return redisService.getObject(key, Object.class);
    }

    // 设置列表
    @PostMapping("/setList")
    public String setList(@RequestParam String key, @RequestBody List<Object> list) {
        redisService.setList(key, list);
        return "List set successfully";
    }

    // 获取列表
    @GetMapping("/getList")
    public List<Object> getList(@RequestParam String key) {
        return redisService.getList(key);
    }

    // 设置集合
    @PostMapping("/setSet")
    public String setSet(@RequestParam String key, @RequestBody Set<Object> set) {
        redisService.setSet(key, set);
        return "Set set successfully";
    }

    // 获取集合
    @GetMapping("/getSet")
    public Set<Object> getSet(@RequestParam String key) {
        return redisService.getSet(key);
    }

    // 设置哈希表
    @PostMapping("/setHash")
    public String setHash(@RequestParam String key, @RequestBody Map<Object, Object> map) {
        redisService.setHash(key, map);
        return "Hash set successfully";
    }

    // 获取哈希表
    @GetMapping("/getHash")
    public Map<Object, Object> getHash(@RequestParam String key) {
        return redisService.getHash(key);
    }
       // 删除键
    @DeleteMapping("/deleteKey")
    public String deleteKey(@RequestParam String key) {
        redisService.deleteKey(key);
        return "Key deleted successfully";
    }
}

6. 启动类

创建一个启动类来启动 Spring Boot 应用程序:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RedisApplication {

    public static void main(String[] args) {
        SpringApplication.run(RedisApplication.class, args);
    }
}

http://www.kler.cn/a/399103.html

相关文章:

  • 使用win32com将ppt(x)文件转换为pdf文件
  • java.sql.SQLException Parameter index out of range
  • 【网络安全面经】OSI七层模型每层都有什么协议
  • 【项目开发】理解SSL延迟:为何HTTPS比HTTP慢?
  • 《操作系统 - 清华大学》3 -3:连续内存分配:内存碎片与分区的动态分配
  • 若点集A=B则A必能恒等变换地变为B=A这一几何常识推翻直线(平面)公理
  • 【MySQL】MySQL的笛卡尔积现象是什么?简单说说
  • Django数据写入MySQL数据库
  • 蓝牙 HFP 协议详解及 Android 实现
  • 用 Python 从零开始创建神经网络(八):梯度、偏导数和链式法则
  • Elasticsearch基本概念及使用
  • css:修改盒子样式
  • vue3 查看word pdf excel文件
  • 【论文阅读】(Security) Assertions by Large Language Models
  • # JAVA中的Stream学习
  • STM32设计防丢防摔智能行李箱
  • 计算机毕业设计 | springboot+vue大学城水电管理系统 校园学校物业水电管理(附源码+文档)
  • Spring:IoC/DI加载properties文件
  • opencv kdtree pcl kdtree 效率对比
  • Linux中开启 Vim 之旅:从快捷键到插件的实用手册
  • Android【01】TRTC实现跨应用屏幕录制
  • STL序列式容器之list
  • 企业案例:钉钉宜搭对接金蝶云星空
  • HTML5拖拽API学习 托拽排序和可托拽课程表
  • 使用CNN进行验证码识别:深度学习与图像预处理教程
  • conda创建 、查看、 激活、删除 python 虚拟环境