SpringBoot笔记:集成Redis

Redis对于SpringBoot也有很好的支持,直接使用对应的依赖 spring-boot-starter-data-redis 即可。在application.properties文件中配置好对应的连接信息后,直接在代码中使用注解 @Autowired 将默认的Redis客户端RedisTemplate加载上来就可以用了,非常方便。

1. pom依赖

<!-- SpringBoot集成Redis起步依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.7.3</version>
</dependency>

2. 配置Redis连接信息

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

# 设置Redis的连接配置信息
spring.redis.host=xxx.xxx.xxx.xxx
spring.redis.port=6379
spring.redis.password=123456

3. Redis使用

最常用的Redis操作就是添加和获取Redis数据,代码中直接使用注解 @Autowired 加载SpringBoot提供的默认Redis客户端RedisTemplate即可,对应于Redis的数据类型,opsForValue指的是String类型,其他类型则是见名知意,如:opsForList、opsForSet、opsForHash等。

package com.yun.demo.service.impl;

import com.yun.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class StudentServiceImpl implements StudentService {
    // SpringBoot提供了默认加载的Redis客户端对象,指定类型建议就使用<Object, Object>
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public void put(String key, String value) {
        // opsForValue()指的是操作String类型的数据,添加数据用set方法
        redisTemplate.opsForValue().set(key, value);
    }

    @Override
    public String get(String key) {
        // 获取数据用get方法
        String value = (String) redisTemplate.opsForValue().get(key);
        return value;
    }
}
posted @ 2022-11-02 21:25  山上下了雪-bky  阅读(117)  评论(0编辑  收藏  举报