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是更好的选择。
相关推荐
艾伦~耶格尔2 小时前
Spring Boot 三层架构开发模式入门
java·spring boot·后端·架构·三层架构
man20172 小时前
基于spring boot的篮球论坛系统
java·spring boot·后端
攸攸太上3 小时前
Spring Gateway学习
java·后端·学习·spring·微服务·gateway
罗曼蒂克在消亡4 小时前
graphql--快速了解graphql特点
后端·graphql
潘多编程4 小时前
Spring Boot与GraphQL:现代化API设计
spring boot·后端·graphql
大神薯条老师4 小时前
Python从入门到高手4.3节-掌握跳转控制语句
后端·爬虫·python·深度学习·机器学习·数据分析
2401_857622665 小时前
Spring Boot新闻推荐系统:性能优化策略
java·spring boot·后端
知否技术5 小时前
为什么nodejs成为后端开发者的新宠?
前端·后端·node.js
AskHarries5 小时前
如何优雅的处理NPE问题?
java·spring boot·后端
计算机学姐6 小时前
基于SpringBoot+Vue的高校运动会管理系统
java·vue.js·spring boot·后端·mysql·intellij-idea·mybatis