Springboot项目中使用redis的配置

本文详细介绍了如何在Spring Boot项目中整合Redis,包括配置依赖、配置文件、自定义RedisTemplate,以及通过Controller进行数据的存取操作。

程序结构:

一、配置

1. 在pom.xml中添加依赖

pom.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lyy</groupId>
    <artifactId>redis-test</artifactId>
    <version>0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <!--始终从仓库中获取-->
        <!--<relativePath/>-->
    </parent>

    <dependencies>
        <!--web应用基本环境,如mvc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--redis包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
    </dependencies>
</project>

其中,spring-boot-starter-web包含springmvc。

2. 配置application.yml

application.yml文件如下:

server:
  port: 11011
  servlet:
    context-path: /api/v1

spring:
  redis:
    # Redis数据库索引(默认为0)
    database: 0
    # Redis服务器地址
    host: 127.0.0.1
    # Redis服务器连接端口
    port: 6379
#     Redis服务器连接密码(默认为空)
#    password: 123456

3. 通过配置类,设置redis

RedisConfig类如下:

package com.apollo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author :apollo
 * @since :Created in 2019/2/22
 */
@Configuration
@EnableCaching
public class RedisConfig {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 自定义springSessionDefaultRedisSerializer对象,将会替代默认的SESSION序列化对象。
     * 默认是JdkSerializationRedisSerializer,缺点是需要类实现Serializable接口。
     * 并且在反序列化时如果异常会抛出SerializationException异常,
     * 而SessionRepositoryFilter又没有处理异常,故如果序列化异常时就会导致请求异常
     */
    @Bean(name = "springSessionDefaultRedisSerializer")
    public GenericJackson2JsonRedisSerializer getGenericJackson2JsonRedisSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }

    /**
     * JacksonJsonRedisSerializer和GenericJackson2JsonRedisSerializer的区别:
     * GenericJackson2JsonRedisSerializer在json中加入@class属性,类的全路径包名,方便反系列化。
     * JacksonJsonRedisSerializer如果存放了List则在反系列化的时候,
     * 如果没指定TypeReference则会报错java.util.LinkedHashMap cannot be cast。
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);

        // 使用Jackson2JsonRedisSerialize 替换默认序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =
                            new Jackson2JsonRedisSerializer(Object.class);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        // 设置value的序列化规则和 key的序列化规则
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setEnableDefaultSerializer(true);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

 

二、逻辑代码

1. 程序入口

package com.apollo;

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

/**
 * @author :apollo
 * @since :Created in 2019/2/22
 */
@SpringBootApplication
public class Application  {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

2. 实体类

实体类Animal如下:

package com.apollo.bean;

/**
 * @author :apollo
 * @since :Created in 2019/2/22
 */
public class Animal {
    private Integer weight;
    private Integer height;
    private String name;

    public Animal(Integer weight, Integer height, String name) {
        this.weight = weight;
        this.height = height;
        this.name = name;
    }

    ……这里是get、set方法
}

3. 公共返回类

package com.apollo.common;

/**
 * @author :apollo
 * @since :Created in 2019/2/22
 */
public class ApiResult {
    public static final Integer STATUS_SUCCESS = 0;
    public static final Integer STATUS_FAILURE = -1;

    public static final String DESC_SUCCESS = "操作成功";
    public static final String DESC_FAILURE = "操作失败";

    private Integer status;
    private String desc;
    private Object result;

    private ApiResult() {}

    private ApiResult(Integer status, String desc, Object result) {
        this.status = status;
        this.desc = desc;
        this.result = result;
    }

    //这个方法和Builder设计模式二选一即可,功能是重复的
    public static ApiResult success(Object result) {
        return success(DESC_SUCCESS, result);
    }

    //同上
    public static ApiResult success(String desc, Object result) {
        return new ApiResult(STATUS_SUCCESS, desc, result);
    }

    //同上
    public static ApiResult failure(Integer status) {
        return failure(status, null);
    }

    //同上
    public static ApiResult failure(Integer status, String desc) {
        return failure(status, desc, null);
    }

    //同上
    public static ApiResult failure(Integer status, String desc, Object result) {
        return new ApiResult(status, desc, result);
    }

    public static Builder builder() {
        return new Builder();
    }

    //静态内部类,这里使用Builder设计模式
    public static class Builder {
        private Integer status;
        private String desc;
        private Object result;

        public Builder status(Integer status) {
            this.status = status;
            return this;
        }

        public Builder desc(String desc) {
            this.desc = desc;
            return this;
        }

        public Builder result(Object result) {
            this.result = result;
            return this;
        }

        public ApiResult build() {
            return new ApiResult(status, desc, result);
        }
    }

    ……这里是get、set方法,这里的方法一定不能少,否则返回时无法将对象序列化
}

4. 请求处理Controller

RedisController类如下:

package com.apollo.controller;

import com.apollo.bean.Animal;
import com.apollo.common.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author :apollo
 * @since :Created in 2019/2/22
 */
@RestController
@RequestMapping(value = "/redis")
public class RedisController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 测试向redis中添加数据
     * @param id
     * @return
     */
    @GetMapping(value = "/{id}")
    public ApiResult addData2Redis(@PathVariable("id") Integer id) {

        redisTemplate.opsForValue().set("first", id);
        redisTemplate.opsForValue().set("second", "hello world");
        redisTemplate.opsForValue().set("third",
                new Animal(100, 200, "二狗子"));

        return ApiResult.builder()
                        .status(ApiResult.STATUS_SUCCESS)
                        .desc("添加成功")
                        .build();
    }

    /**
     * 测试从redis中获取数据
     * @return
     */
    @GetMapping("/redis-data")
    public ApiResult getRedisData() {
        Map<String, Object> result = new HashMap<>();
        result.put("first", redisTemplate.opsForValue().get("first"));
        result.put("second", redisTemplate.opsForValue().get("second"));
        result.put("third", redisTemplate.opsForValue().get("third"));

        return ApiResult.builder()
                .status(ApiResult.STATUS_SUCCESS)
                .desc("获取成功")
                .result(result)
                .build();
    }
}

注意:这里是返回ApiResult对象,需要将返回的对象序列化,所以ApiResult中的get/set方法是必须的,否则会报错:HttpMessageNotWritableException: No converter found for return value of type: class com.apollo.common.ApiResult,找不到ApiResult类型的转换器。

三、测试

1. 测试添加

使用postman请求http://localhost:11011/api/v1/redis/5,返回结果:

{
    "status": 0,
    "desc": "添加成功",
    "result": null
}

登录到redis,使用命令dbsize查看存储的数据量:

数据量为3,对应我们上边程序中的3步操作。

2. 测试获取

使用postman请求http://localhost:11011/api/v1/redis/redis-data,返回结果:

{
    "status": 0,
    "desc": "获取成功",
    "result": {
        "third": {
            "weight": 100,
            "height": 200,
            "name": "二狗子"
        },
        "first": 5,
        "second": "hello world"
    }
}

与我们之前存入的数据对比,是正确的。

四、代码地址

github地址:https://github.com/myturn0/redis-test.git

<think>嗯,用户想了解在Spring Boot项目中如何集成和使用Redis。首先,我需要回忆一下Spring Boot和Redis整合的基本步骤。记得需要添加相关的依赖,比如Spring Data Redis,可能还有Lettuce或者Jedis的客户端。用户提供的引用里提到,Spring Data Redis需要Redis 2.6及以上和Java SE 8.0以上,而且现在默认使用Lettuce作为响应式连接器。所以可能需要先确认依赖配置。 然后,配置Redis连接信息应该是通过application.properties或者application.yml文件,设置主机、端口、密码之类的。可能还要提到不同的操作模式,比如单机、哨兵、集群,根据引用中的内容,用户可能需要了解这些模式的基本配置方法。 接下来,可能需要讲解如何创建RedisTemplate或者StringRedisTemplate来操作数据。用户可能对如何存取数据,比如字符串、哈希、列表等结构感兴趣。此外,响应式编程的部分可能需要单独说明,特别是使用ReactiveRedisTemplate的情况,不过根据用户的问题,可能先以同步方式为主。 另外,缓存抽象也是一个重点,可以通过@EnableCaching和@Cacheable等注解来简化缓存的使用。需要提到如何配置缓存管理器,可能使用RedisCacheManager。用户可能对如何开启缓存支持,以及如何应用在方法上比较关注。 还要注意版本兼容性问题,用户引用的资料中提到了Spring Boot 2.3.0,所以需要确认依赖是否匹配。比如在pom.xml中指定正确的Spring Boot版本,并引入spring-boot-starter-data-redis。可能还需要提到排除默认的Lettuce,如果用户想用Jedis的话,不过现在默认是Lettuce,可能不需要特别处理,除非用户有需求。 可能还需要给出一个简单的示例代码,比如如何注入RedisTemplate,进行set和get操作。此外,配置类的编写可能也是一个步骤,但Spring Boot自动配置可能已经处理了大部分内容,所以可能只需要在配置文件中设置参数即可。 最后,用户可能需要了解常见的问题排查,比如连接不上Redis时的检查步骤,或者序列化方式的配置,避免存储乱码。可能还需要提到测试,比如写一个单元测试来验证Redis操作是否正常。 总结一下,步骤大概是:添加依赖、配置连接信息、使用RedisTemplate操作数据、配置缓存注解、处理序列化、示例代码和常见问题。需要确保引用的内容正确,比如引用中提到的自动配置和连接器信息,要正确标注引用来源。同时,生成的相关问题可能需要包括配置多模式、选择客户端、缓存注解使用和性能优化等方向。</think>### 在Spring Boot项目中集成和使用Redis的步骤 #### 1. 添加依赖 在`pom.xml`中添加Spring Data Redis和Lettuce(默认的响应式连接器)依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 确保Spring Boot版本为2.3.0或更高[^3]。 #### 2. 配置Redis连接信息 在`application.properties`或`application.yml`中配置Redis服务器信息: ```properties # 单机模式配置 spring.redis.host=localhost spring.redis.port=6379 spring.redis.password=your_password ``` 若需集群或哨兵模式,需调整配置参数[^2]。 #### 3. 使用RedisTemplate操作数据 注入`RedisTemplate`或`StringRedisTemplate`进行数据操作: ```java @Autowired private RedisTemplate<String, Object> redisTemplate; public void setValue(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object getValue(String key) { return redisTemplate.opsForValue().get(key); } ``` #### 4. 响应式编程支持(可选) 若需响应式操作,注入`ReactiveRedisTemplate`: ```java @Autowired private ReactiveRedisTemplate<String, String> reactiveTemplate; public Mono<Boolean> setValueReactive(String key, String value) { return reactiveTemplate.opsForValue().set(key, value); } ``` 需确保使用Lettuce连接器。 #### 5. 配置缓存抽象 通过注解启用缓存并配置Redis缓存管理器: ```java @Configuration @EnableCaching public class RedisConfig { @Bean public RedisCacheManager cacheManager(RedisConnectionFactory factory) { return RedisCacheManager.create(factory); } } // 使用缓存注解 @Service public class UserService { @Cacheable(value = "users", key = "#id") public User getUserById(String id) { // 数据库查询逻辑 } } ``` #### 6. 处理序列化 默认使用JDK序列化,可自定义JSON序列化: ```java @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer()); return template; } ``` #### 7. 验证连接 编写测试类验证Redis操作: ```java @SpringBootTest public class RedisTest { @Autowired private RedisTemplate<String, String> redisTemplate; @Test void testSetAndGet() { redisTemplate.opsForValue().set("testKey", "Hello Redis"); assertEquals("Hello Redis", redisTemplate.opsForValue().get("testKey")); } } ``` ### 常见问题排查 - **连接失败**:检查Redis服务状态、防火墙设置及密码配置。 - **序列化错误**:确保键值类型与序列化器匹配。 - **性能问题**:使用连接池或调整Lettuce参数(如超时时间)。 ---
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值