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是更好的选择。
相关推荐
阿祖zu19 分钟前
芝士就是力量!开源私有化部署与 GitHub 双向同步的个人知识笔记 App
前端·后端·ios
不才不才不不才29 分钟前
Spring 源码系列(16): doDispatch 全流程——一次请求的主干链路
java·后端·spring
IT_陈寒36 分钟前
SpringBoot自动配置失效?这个隐藏配置坑了我一整晚
前端·人工智能·后端
搜狐技术产品小编20231 小时前
告别“黑盒”与误判:如何用“多智能体对抗辩论”重构内容安全审核系统
后端·多agent
DantyWei1 小时前
controller注册及调用时机
后端
edwarddamon1 小时前
Spring Cloud 配置热更新与 Bean 代理机制梳理
java·后端
码事漫谈2 小时前
我用 Seed Evolving 做了个 AI 小说写作工具
后端
Raas1002 小时前
MAIGateway,魔芋企业级AI网关的FinAPI成本竞争力设计
java·后端·网关·api网关·魔芋ai·finapi·mai gateway
计算机魔术师3 小时前
传统基础架构 - 微服务
大数据·后端·微服务·架构·开发工具·编程语言
DantyWei3 小时前
kube-controller-manager的leader选举流程和策略
后端