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是更好的选择。
相关推荐
用户2986985301436 分钟前
Python 将 Word 文档转换为 XML 的实践要点
后端·python·api
Java爱好狂.1 小时前
阿里1658页Java面试题总结(含答案)
java·后端·高并发·架构师·java面试·java面试题·java八股文
vipxieliang1 小时前
PHP Swoole 协程模型详解:协程与线程/进程、调度、常驻内存及与 Go goroutine 的异同
后端·php
lazy H1 小时前
【计算机网络】第 12 篇:IPv6 详解——地址格式、地址类型与双栈网络
网络·经验分享·后端·学习·计算机网络·408
Rain的Java大神之路2 小时前
LeetCode 21 合并两个有序链表:一道 Easy 题,凭什么刷掉一半候选人?
java·后端·算法
w_t_y_y2 小时前
JWT(5)JWT+spring security
java·后端·spring
念何架构之路2 小时前
OpenTelemetry核心概念
后端·目标跟踪·golang·c#·linq
IT_陈寒2 小时前
Java项目实战经验分享:一次由JPA懒加载引发的生产事故
前端·人工智能·后端
环境栈笔记2 小时前
浏览器多开同步怎么做?先分清设置、登录态和窗口操作
前端·人工智能·后端·自动化