spring boot 2.7.0 整合redis(三)

什么是Redis

redis是一个高性能的key-value存储系统,支持String,list,set等集合。为了保证读取效率,数据都是缓存在内存中。

​通常我们将经常需要读取字典的数据,用户的登录的凭证信息,或者需要高速处理的并发数据可以使用redis进行读取,增加系统的性能,减少服务器的处理压力。

本教程使用版本及必要条件

spring boot 2.7.0

Redis-x64-3.2.100.rar

​在使用spring boot连接redis连接前,首先保证您的redis服务正常运行,且可以使用工具或命令连接。可以使用RedisDesktopManager图形化工具连接并管理redis。

创建项目

新建一个spring boot 项目。可以通过我之前的教程创建一个空项目。

Spring Boot 新手入门

编辑pom文件

在idea中新建一个maven项目后,首先需要在pom文件中引入如下依赖。

主要包含:web 依赖,redis依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath/>
    </parent>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

不要忘记重新加载一下依赖,防止找不到jar包!依次点击maven,项目名称=》右键=》Reimport

在这里插入图片描述

目录结构

建立好如下图的包目录结构,具体如下:

在这里插入图片描述

配置redis服务地址

修改application.properties配置文件中关于redis的配置。默认无密码。

################ Redis ##############
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 链接超时时间 单位 ms(毫秒)
spring.redis.timeout=3000ms

实体类

在com.study.model包下编写一个实体类TestDataVO,其中包含 姓名 和年龄两个字段,用于测试在redis中读写list。代码如下:

package com.study.model;

import java.io.Serializable;

public class TestDataVO implements Serializable {

    private String name;
    private int age;

    public TestDataVO(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Redis序列化器LettuceRedisConfig

在com.study.config包下编辑LettuceRedisConfig类,该类将RedisTemplate注入到spring中并设置key和value的序列化器,这里使用LettuceConnectionFactory获取连接。代码如下:

package com.study.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
/**
 * LettuceRedis 配置文件
 * 设置序列化器
 */
@Configuration
public class LettuceRedisConfig {
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }
}

启动及测试类

在com.study 中编写MyApplication类,用于spring boot启动及测试数据存放redis中,代码如下:

package com.study;
import com.study.model.TestDataVO;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@EnableAutoConfiguration
public class MyApplication {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 测试接口 先将time存入redis 再从redis取出该值并返回
     * 38081是配置文件默认端口 可以在 application.properties中修改端口号
     * http://localhost:38081/addKey
     * @return
     */
    @RequestMapping("addKey")
    public Map<String, Object> addKey(){
        Map<String, Object> rsMap = new HashMap<>();
        long time = System.currentTimeMillis();
        String key = "time";
        //time 为key 存入 redis 2分钟后失效 不失效请取消后两个参数
        redisTemplate.opsForValue().set(key,time,2, TimeUnit.MINUTES);
        //将键为time的值取出 存入返回map
        rsMap.put("time", redisTemplate.opsForValue().get(key));
        return rsMap;
    }

    /**
     * 测试接口 将对象数组存入redis 从redis取出该值后返回
     * http://localhost:38081/addList
     * @return
     */
    @RequestMapping("addList")
    public Map<String, List<TestDataVO>> addList(){
        Map<String, List<TestDataVO>> rsMap = new HashMap<>();
        TestDataVO testDataVO = new TestDataVO("张三", 16);
        TestDataVO testDataVO1 = new TestDataVO("李四", 18);
        List<TestDataVO> list = new ArrayList<>();
        list.add(testDataVO);
        list.add(testDataVO1);
        //将集合存入到list中
        redisTemplate.opsForList().rightPushAll("testList", list);

        //从redis中取出数据
        List<TestDataVO> redisData = redisTemplate.opsForList().range("testList",0,-1);
        rsMap.put("testList", redisData);
        return rsMap;
    }

    /**
     * 测试接口 删除key
     * http://localhost:38081/addList
     * @return
     */
    @RequestMapping("removeKey")
    public Map<String, Object> removeKey(){
        Boolean rs = redisTemplate.delete("testList");
        Map<String, Object> rsMap = new HashMap<>();
        rsMap.put("rs", rs);
        return rsMap;
    }

    /**
     * 启动入口
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class);
    }
}

测试

右键运行MyApplication类。观察控制台输出如下,观察项目正常启动:

在这里插入图片描述

打开浏览器,输入如下地址进行接口测试,选择一个将数据插入redis的接口:http://localhost:38081/addKey

在这里插入图片描述

将对象数组存入redis并取出接口:http://localhost:38081/addList

删除key接口: http://localhost:38081/removeKey

好了,spring boot整合redis基本完成。

写在最后

开源是一种美德,尽早加入开源社区,共建美好生态!

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
要在Spring Boot 2.7.0中连接Redis,您需要完成以下步骤: 1. 添加Redis依赖项:在pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置Redis连接信息:在application.properties文件中添加以下配置信息: ```properties spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= ``` 3. 创建RedisTemplate Bean:创建RedisTemplate Bean以便在应用程序中使用Redis。以下是示例代码: ```java @Configuration public class RedisConfig { @Bean public RedisConnectionFactory redisConnectionFactory() { return new LettuceConnectionFactory(); } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory()); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class)); return redisTemplate; } } ``` 4. 在应用程序中使用Redis:在您的应用程序中,您可以使用自动装配来注入RedisTemplate Bean,并使用以下代码执行Redis操作: ```java @Autowired private RedisTemplate<String, Object> redisTemplate; public void put(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } ``` 这是在Spring Boot 2.7.0中连接Redis的基本步骤。您可以根据需要进行更改和调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

y打伞的鱼y

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

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

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

打赏作者

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

抵扣说明:

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

余额充值