SpringBoot集成redis

本文详细介绍了如何在Spring Boot应用中整合Redis,包括添加相关依赖、配置Redis连接参数,以及创建RedisUtils工具类实现缓存的增删查改操作。通过示例展示了如何在Controller中调用这些方法进行实际使用。

1.添加依赖

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

2.添加配置

# REDIS (RedisProperties)
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# Redis数据库索引(默认为0)
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
spring.redis.lettuce.shutdown-timeout=0

3.添加工具方法

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

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;

@Service
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 写入缓存 * @param key * @param value * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存设置时效时间 * @param key * @param value * @return
     */
    public boolean setEx(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 判断缓存中是否有对应的value * @param key * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存 * @param key * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    /**
     * 删除对应的value * @param key
     */
    public boolean remove(final String key) {
        if (exists(key)) {
            Boolean delete = redisTemplate.delete(key);
            return delete;
        }
        return false;

    }
}

使用方法

import com.example.repeat_submission.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @Autowired
    RedisUtils redisUtils;

    @GetMapping("test")
    public Object test(@RequestParam(value = "id") String id) {
        redisUtils.set("ninesun", id);
        return redisUtils.get("ninesun");
    }
}

至此redis的配置以及具体如何使用的讲解就结束啦

Spring Boot 项目中集成 Redis 数据库,主要涉及以下几个步骤:引入依赖、配置 Redis 连接信息、使用 `RedisTemplate` 或 `StringRedisTemplate` 来操作 Redis 数据库。 ### 引入 Redis 依赖 在 `pom.xml` 文件中添加以下依赖以集成 Redis: ```xml <!-- Redis 依赖 --> <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 交互的底层操作,并提供连接池功能以优化与 Redis 的连接管理,提高性能[^1]。 ### 配置 Redis 连接 在 `application.properties` 或 `application.yml` 文件中配置 Redis 的连接信息。以下是 `application.properties` 的示例配置: ```properties # Redis 配置 spring.redis.host=localhost spring.redis.port=6379 spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.min-idle=2 spring.redis.lettuce.pool.max-wait=2000ms ``` 如果使用 `application.yml`,则配置如下: ```yaml spring: redis: host: localhost port: 6379 lettuce: pool: max-active: 8 max-idle: 8 min-idle: 2 max-wait: 2000ms ``` 这些配置项用于指定 Redis 服务器的地址、端口以及连接池的相关参数。 ### 使用 RedisTemplate 操作 RedisSpring Boot 应用程序中,可以通过注入 `RedisTemplate` 来操作 Redis 数据库。下面是一个简单的示例,展示如何使用 `RedisTemplate` 设置和获取数据: ```java import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @Service public class RedisService { private final RedisTemplate<String, Object> redisTemplate; public RedisService(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } public void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } } ``` 在这个示例中,`RedisTemplate` 被用来执行基本的键值对操作。`opsForValue()` 方法返回一个 `ValueOperations` 对象,可以用来设置和获取字符串类型的值。 ### 分布式会话场景(Redis-Session) 对于需要支持分布式会话的应用程序,可以利用 Spring Session 提供的功能,通过 Redis 来存储会话信息。这通常涉及到额外的配置和依赖项,但可以极大地简化跨多个服务实例的会话管理。 通过以上步骤,可以在 Spring Boot 项目中成功集成 Redis 数据库,并利用其提供的高性能数据访问能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ZNineSun

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

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

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

打赏作者

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

抵扣说明:

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

余额充值