Redis数据储存

1.概述

  • REmote DIctionary Server(Redis) 是一个由 Salvatore Sanfilippo 写的 key-value 存储系统,是跨平台的非关系型数据库。

  • Redis 通常被称为数据结构服务器,因为值(value)可以是字符串(String)、哈希(Hash)、列表(list)、集合(sets)和有序集合(sorted sets)等类型。

2.配置

在官网下载Redis-x64-xxx.zip压缩包,解压后进入其中的目录,将环境变量设置到此电脑中,在Path中添加刚才的安装目录:

1
C:\xxx\xxx\Redis-x64-xxx

3.启动

在cmd中输入:

1
redis-server

image-20241216103207632

如图显示在本机开放的端口号。

这时候另启一个 cmd 窗口,原来的不要关闭,不然就无法访问服务端了。

切换到 redis 目录下运行:

1
redis-cli.exe -h 127.0.0.1 -p 6379

设置键值对:

1
set abc efg

取出键值对:

1
get abc

image-20241216103707273

4.Spring配置

在配置文件中添加:

1
2
3
4
redis:
host: "localhost"
port: 6379
timeout: 5000

添加redis模板类:RedisTemplate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

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.RedisSerializer;

@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
RedisSerializer<Object> serializer = new GenericJackson2JsonRedisSerializer();
template.setDefaultSerializer(serializer);
return template;
}
}

添加键值对:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.kd_13.qq_fake.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/redis")
public class RedisController {

@Autowired
private RedisTemplate<String, String> redisTemplate;

@PostMapping("/postkey")
public ResponseEntity<String> postKey(@RequestParam String key, @RequestParam String value) {
redisTemplate.opsForValue().set(key, value);
return ResponseEntity.ok("Key-value pair saved to Redis");
}

@GetMapping("/getvalue")
public ResponseEntity<String> getValue(@RequestParam String key) {
String value = redisTemplate.opsForValue().get(key);
if (value == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Key not found");
}
return ResponseEntity.ok(value);
}
}

其中核心的为:

1
redisTemplate.opsForValue().set(key, value);
1
String value = redisTemplate.opsForValue().get(key);