0
点赞
收藏
分享

微信扫一扫

SpringBoot (六) --------- SpringBoot 集成 Redis

DYBOY 2022-03-18 阅读 29

目录


Redis 是一个 NoSQL 数据库, 常作用缓存 Cache 使用。

通过 Redis 客户端可以使用多种语言在程序中,访问 Redis 数据。

Java 语言中使用的客户端库有 Jedis、lettuce、 Redisson 等。

Spring Boot 中使用 RedisTemplate 模版类操作 Redis 数据


完成目标 : 使用 SpringBoot 来完成在 Redis 中添加和查询数据,熟悉 Redis 在 SpringBoot 中的使用

一、配置 Redis

我们在 windows 系统中中双击 redis-server.exe 启动 redis 服务端( windows 更适合于学习环境)
在这里插入图片描述
启动 redis 客户端,通过客户端访问数据

在这里插入图片描述

二、创建项目

  • 项目名 : springboot-redis

在这里插入图片描述
在这里插入图片描述

  • pom.xml
 <!--redis 起步依赖 spring boot 会在容器中创建两个对象 RedisTemplate ,StringRedisTemplate -->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
 </dependency>
  • 核心配置文件 application.properties
#指定 redis
spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=aszhou123
  • 创建 RedisController

在程序中使用 RedisTemplate类的方法 操作redis数据, 实际就是调用的 lettuce 客户端的中的方法。

package com.fancy.springbootredis.controller;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class RedisController {

    // 注入 RedisTemplate
    // 泛型 key, value 都是 String , 或者 Object , 又或者不写

    @Resource
    private RedisTemplate redisTemplate;

    // 添加数据到 Redis
    @PostMapping("/redis/data/{name}/{classId}")
    public String addToRedis(@PathVariable String name, @PathVariable  String classId) {
        // 操作Redis 中String 类型数据, 先获取ValueOperation 对象

        ValueOperations valueOperations = redisTemplate.opsForValue();

        // 添加数据到 Redis

        valueOperations.set("name", name);
        valueOperations.set("classId", classId);

        return "向 Redis 添加 String 类型数据";
    }
    @GetMapping("/redis/data/{key}")
    public String getValue(@PathVariable  String key) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object value = valueOperations.get(key);
        return "key 是 " + key + ", value 是" + value.toString();
    }
}

之后我们使用 HTTP Client 模拟发送请求,结果如下
在这里插入图片描述

在这里插入图片描述
然后,我们对代码进行修改,使用 StringRedisTemplate 类进行添加和查询

package com.fancy.springbootredis.controller;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class RedisController {

    // 注入 RedisTemplate
    // 泛型 key, value 都是 String , 或者 Object , 又或者不写

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 添加数据到 Redis
    @PostMapping("/redis/data/{stuName}/{stuId}")
    public String addToRedis(@PathVariable String stuName, @PathVariable  String stuId) {
        // 操作Redis 中String 类型数据, 先获取ValueOperation 对象

        ValueOperations valueOperations = stringRedisTemplate.opsForValue();

        // 添加数据到 Redis

        valueOperations.set("stuName", stuName);
        valueOperations.set("stuId", stuId);

        String s = "向 Redis 添加 String 类型数据";
        return s;
    }
    @GetMapping("/redis/data/{key}")
    public String getValue(@PathVariable  String key) {
        ValueOperations valueOperations = stringRedisTemplate.opsForValue();
        Object value = valueOperations.get(key);
        return "key 是 " + key + ", value 是" + value.toString();
    }

}

在这里插入图片描述
测试结果如图
在这里插入图片描述
在这里插入图片描述

三、对比 StringRedisTemplate 和 RedisTemplate

我们先来介绍什么是序列化与反序列化 :

为什么需要序列化 ?

什么情况下需要序列化 ?

序列化的方式

Java的序列化: 把 Java 对象转为 byte[], 二进制数据

JSON 序列化:JSON 序列化功能将对象转换为 JSON 格式 或从 JSON 格式转换对象。

例如把一个 Student 对象转换为 JSON 字符串 {"name":"李四", "age":29}
反序列化将JSON字符串 {"name":"李四", "age":29} 转换为 Student 对象

两者对比

StringRedisTemplate 把k,v 都是作为String处理, 使用的是String的序列化 , 可读性好

名称异同
StringRedisTemplateStringRedisTemplate 把 k、v 都是作为 String 处理,使用的是String的序列化,可读性好
RedisTemplate把 k、v 经过了序列化存到 Redis中,k、v 是序列化的内容, 不能直接识别.。默认使用的JDK序列化, 可以修改为其他的序列化方式

设置key或者value的序列化方式

// 使用 RedisTemplate, 在存取值之前, 设置序列化
// 设置 key 使用 String 的序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());

// 设置 value 的序列化
redisTemplate.setValueSerializer(new StringRedisSerializer());

redisTemplate.opsForValue().set(k, v);

IDEA 生成序列化版本号

Setting ----> 搜索 serializable 将下方配置勾选
在这里插入图片描述
IDEA :alt + enter 中有添加序列化版本号等功能
在这里插入图片描述
生成序列化版本号如下
在这里插入图片描述

设置 JSON 序列化

@PostMapping("/redis/student")
public String addJson() {
    Student student = new Student();
    student.setId("1001");
    student.setName("zhangsan");
    student.setAge(20);
    redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Student.class));
    redisTemplate.opsForValue().set("mystudent", student);
    return "json序列化"; 
}
举报

相关推荐

0 条评论