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是更好的选择。
相关推荐
斑鸠喳喳几秒前
交换器 Exchanger
后端
霸道流氓气质几秒前
MinIO 入门与实战:S3 兼容对象存储、Spring Boot 集成与 AI 应用文件管理
人工智能·spring boot·后端
我真是泰库辣1 分钟前
我写了 300 行 Python,让代码替我在《三角洲行动》里吹口琴
后端
CaptainT2 分钟前
先把例子跑起来:MySQL 环境与本文的示例数据
数据库·后端·mysql
程序猿乐锅3 分钟前
【从0-1学习Python | 第四篇】Python 字符串和元组
java·开发语言·笔记·后端·python·学习
码事漫谈16 分钟前
一条 ALTER TABLE 的跨库旅程:KFS 如何自动翻译 DDL
后端
Rain的Java大神之路29 分钟前
10 万人抢 2000 个座位,电影票选座系统怎么防超卖?一文讲透大厂高频场景题
java·后端·面试
武子康31 分钟前
用户说“算了”,设备指令真的取消了吗?
人工智能·后端·agent
威哥爱编程37 分钟前
【AI全栈12-07】Spring Boot 用 Agent 自动完成多步运营任务
java·spring boot·后端
未秃头的程序猿40 分钟前
我用 Spring AI + MCP 把公司内部系统接给了 AI,过程没想象中顺利
java·后端