SpringBoot整合Redis

前期工作

下载安装,开启Redis服务

步骤:Redis下载安装-CSDN博客

一.搭建SpringBoot项目

使用Spring initializr创建

二.引入Redis依赖

创建完后,可以在pom.xml中看到Redis的依赖,该依赖提供了RedisTemplate的使用功能,可以通过RedisTemplate对Redis进行操作。

复制代码
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
 </dependency>

在test中测试Redis是否成功

首先启动本地Redis服务(也可以用本地电脑中的"服务"界面去启动)

三.测试Redis的基本操作

详解 RedisTemplate 的 API方法,如后文附加

在测试类中基本操作

通常我们项目存储的是对象进行操作,所以可以通过Spring封装的Redis,可以将Java对象存入Redis中,而取出来之后也只需要强转一下就OK,案例如下

复制代码
package com.example.springredis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringRedisApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private Student student,student2;    //自动生成两个对象

    @Test
    public void testSetRedis(){
        //1.存入普通键值对数据
        redisTemplate.boundValueOps("name").set("zhangsan");
        redisTemplate.opsForValue().set("a",1);


        //2.在redis中存入对象
        student.setName("zhangsan");
        student.setAge(19);
        //redisTemplate.opsForValue()方法存储对象
        redisTemplate.opsForValue().set("s1",student);   //将Student对象序列化存储在redis中



    }
    @Test
    public void testGetRedis(){
        //1.获取数据
        Object name=redisTemplate.boundValueOps("name").get();
        int a=(int) redisTemplate.opsForValue().get("a");
        System.out.println(name);
        System.out.println(a);

        //2.获取对象(反序列)
        Student student1=(Student) redisTemplate.opsForValue().get("s1");
        System.out.println(student1);

    }

}

也可以自定义一个RedisUtil操作类,对对象进行操作

首先需要重新定义RedisConfig配置类,该类作用是将RedisTemplate类型的存储类型结构变为redisTemplate<String,Object>。代码如下

复制代码
package com.example.springredis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    /**
     * RedisTemplate配置
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        // 设置序列化
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);

        RedisSerializer<?> stringSerializer = new StringRedisSerializer();
        // key序列化
        redisTemplate.setKeySerializer(stringSerializer);
        // value序列化
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // Hash key序列化
        redisTemplate.setHashKeySerializer(stringSerializer);
        // Hash value序列化
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

然后再自定义一个RedisUtil类

复制代码
package com.example.springredis;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 根据key读取数据
     */
    public Object get(final String key) {
        //不能直接创建,因为RedisTemplate没有配置连接工厂
//        RedisTemplate<String, Object> redisTemplate=new RedisTemplate<>();
        if (StringUtils.isBlank(key)) {
            return null;
        }
        try {
            return redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 写入数据
     */
    public boolean set(final String key, Object value) {
        //不能直接创建,因为RedisTemplate没有配置连接工厂
//        RedisTemplate<String, Object> redisTemplate=new RedisTemplate<>();
        if (StringUtils.isBlank(key)) {
            return false;
        }
        try {
            redisTemplate.opsForValue().set(key, value);
            log.info("存入redis成功,key:{},value:{}", key, value);
            return true;
        } catch (Exception e) {
            log.error("存入redis失败,key:{},value:{}", key, value);
            e.printStackTrace();
        }
        return false;
    }
}

最后去测试这个RedisUtil类,对对象进行操作

复制代码
package com.example.springredis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringRedisApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisUtil redisUtil;   //自定义一个RedisUtil操作类

    @Autowired
    private Student student,student2;    //自动生成两个对象

    @Test
    public void testSetRedis(){

        //3.使用Redis工具类RedisUtil
        student2.setName("李四");
        student2.setAge(20);
        redisUtil.set("s2",student2);

    }
    @Test
    public void testGetRedis(){

        //3.使用Redis工具类从Redis中获取对象
        Student s2=(Student) redisUtil.get("s2");
        System.out.println(s2);

    }

}

四.连接的Redis不是本地,而是其他

需要在application.yaml配置文件中配置Redis连接参数

复制代码
#将来连接的Redis不是本地,需要设置连接参数
spring:
  redis:
    host: 127.0.0.1   #redis主机名
    port: 6379        #端口号
#    password: 123456   #redis的密码

附加:详解 RedisTemplate 的 API方法

1.常用数据操作

若以 bound 开头,则意味着在操作之初就会绑定一个 key,后续的所有操作便默认认为是对该 key 的操作。

相关推荐
星辰徐哥21 小时前
Spring Boot 微服务架构设计与实现
spring boot·后端·微服务
星辰徐哥21 小时前
Spring Boot 数据导入导出与报表生成
spring boot·后端·ui
明夜之约21 小时前
Spring Boot 自动装配源码
java·spring boot·后端
Leaton Lee21 小时前
Spring Boot分层架构详解:从Controller到Service再到Mapper的完整流程
java·spring boot·后端·架构
Micro麦可乐21 小时前
Spring Boot 实战:从零设计一个短链系统(含完整代码与数据库设计)
数据库·spring boot·后端·哈希算法·雪花算法·短链系统
Jinkxs21 小时前
Resilience4j- 与 Spring Boot 快速集成:自动配置与基础注解使用
java·spring boot·后端
毕设源码_郑学姐21 小时前
计算机毕业设计springboot网络相册设计与实现 基于Spring Boot框架的在线相册管理系统开发与应用 Spring Boot驱动的网络影集设计与实践
spring boot·后端·课程设计
辣机小司21 小时前
【踩坑记录:Spring Boot 配置文件读取值不一致?警惕 YAML 的“八进制陷阱”与 SnakeYAML 版本之谜】
java·spring boot·后端·yaml·踩坑记录
一条小锦吕*21 小时前
基于Spring Boot + 数据可视化 + 协同过滤算法的推荐系统设计与实现(源码+论文+部署全讲解)
spring boot·算法·信息可视化
Jinkxs21 小时前
Prometheus - 监控微服务:Spring Boot 应用指标暴露与监控
spring boot·微服务·prometheus