springboot整合redis

redis概述

Redis是一个开源(BSD许可)的、内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件,并提供多种语言的API。 Redis支持多种类型的数据结构,如 字符串(strings)、散列(hashes)、列表(lists)、集合(sets)、有序集合(sorted sets)与范围查询、bitmaps、 hyperloglogs 和 地理空间(geospatial)、索引半径查询。 Redis 内置了复制(replication),LUA脚本(Lua scripting),LRU驱动事件(LRU eviction),事务(transactions) 和不同级别的磁盘持久化(persistence), 并通过 Redis哨兵(Sentinel)和自动 分区(Cluster)提供高可用性(high availability)。

springboot整合redis三部曲

1.依赖

pom.xml 复制代码
//引入redis依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.配置

application.yml 复制代码
#引入redis
redis:
  host: 127.0.0.1
  port: 6379
  database: 7
  password:
  lettuce:
    pool:
      max-active: 20
      max-wait: -1
      max-idle: 5
      min-idle: 0

3.注解--这一步非必须starter机制会自动加载该bean,配置类加载bean一般是为了改写原来的bean或者是加载项目以外的bean

定义上面的依赖以后,springboot给我们提供一个工具模板类:RedisTemplate和StringRedisTemplate对象。但是内部的RedisTemplate的操作的数据的存储的时候,key是object类型。所以就造成一个问题。key名字就进行序列化在存储。就会造成如下问题:

  • 感觉很奇怪
  • 在一些命令操作的就不方便调试
  • 但是不影响程序的操作和获取

覆盖内部的redisTemplate的初始化,让ioc容器加载我的redistemplate的初始化。接下来就自定义RedisConfiguration改写内部的规则。把key的序列化改成String,如下:

RedisConfiguration.java 复制代码
package com.zl.springbootssm.config.redis;
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.StringRedisSerializer;


@Configuration
public class RedisConfiguration {
    /**
     * @return org.springframework.data.redis.core.RedisTemplate<java.lang.String, java.lang.Object>
     * @Author
     * @Description 改写redistemplate序列化规则
     * @Date
     * @Param [redisConnectionFactory]
     **/
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 1: 开始创建一个redistemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 2:开始redis连接工厂跪安了
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 创建一个json的序列化方式
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        // 设置key用string序列化方式**【redis默认是以对象的形式序列化会导致存储的时候不是原本的字符形式,所以需要对原Redistemplate进行改造】**
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //        // 设置value用jackjson进行处理
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // hash也要进行修改
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        // 默认调用
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

什么情况下会使用配置类@configuration?

  • 加载项目以外的bean,放入到ioc容器中可以自定义配置类;
  • 在内部的配置类初始化的类,不满足条件的情况下可以使用配置类去覆盖

4.调用

RedisController.java 复制代码
package com.zl.springbootssm.controller;

import com.zl.springbootssm.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@Slf4j
public class RedisController extends BaseController {

    //这个时候给我放入到ioc容器的
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/redis/set")
    public String loginUser() {
        User user = new User();
        user.setUserName("yykk");
        user.setId(1);
        redisTemplate.opsForValue().set("pug_user", user);
        return "success";
    }
    @GetMapping("/redis/get")
    public User getUser() {
        return (User) redisTemplate.opsForValue().get("pug_user");
    }
}
java 复制代码
package com.zl.springbootssm.controller.session;

import com.zl.springbootssm.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 * Author: Mr.Zhao
 * Create Date Time: 2023/11/22 21:29.
 * Update Date Time:
 */
@RestController
@Slf4j
@RequestMapping("/token")
public class LoginTokenController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @PostMapping ("/login")
    public String saveUser(@RequestBody User user) {
        log.info(String.valueOf(user));
        String key = "token" + UUID.randomUUID().toString();
//        假设账号和密码正确
        stringRedisTemplate.opsForValue().set(key, user.getUserName(), 3600, TimeUnit.SECONDS);
        return key;
    }

    @GetMapping("/info")
    public String getinfo(String token) {
        return "当前登录时" + stringRedisTemplate.opsForValue().get(token);
    }
}

StringRedisTemplate与RedisTemplate区别

  • StringRedisTemplate继承RedisTemplate。
  • redis数据库里面本来存的是字符串数据或者你要存取的数据就是字符串类型数据的时候,那么你就使用 StringRedisTemplate即可。 数据是复杂的对象类型,使用RedisTemplate是更好的选择。
相关推荐
AlienZHOU23 分钟前
AI Coding 时代下,我的技术面试实践分享
前端·后端·面试
狗头大军之江苏分军3 小时前
《潮水漫过十七岁》开学了
后端
苏三说技术3 小时前
如何看待GPT-6在UP主众测中碾压夺冠?它是现在最强大模型吗?
后端
mldong4 小时前
一份 JSON,一条能跑的审批流:把报销流程送上工作流引擎
后端·架构
wno7044 小时前
Spring Boot WebFlux增删改查
java·spring boot·后端
Captaincc4 小时前
AI用量v0.1.11更新发布 新增 jusage doctor 诊断指令 托盘展示token 和余额 新增 AutoClaw 支持
前端·后端·vibecoding
aramae5 小时前
模拟实现strlen()函数 (C语言)
c语言·开发语言·后端
IT_陈寒6 小时前
Python的GIL把我坑惨了,多线程跑得比单线程还慢
前端·人工智能·后端
分支预测失败6 小时前
RISC-V 时间子系统深度专题:mtime 访问路径、SBI 定时器与 Linux tickless 协同
后端
65岁退休Coder6 小时前
PI Agent 开发一个生产级 Harness
后端·node.js·agent