1.项目结构目录
2.pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.hxl</groupId>
<artifactId>springboot_redis</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot_redis</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.10</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<!-- Spring Web 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Data Redis 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 连接池(可选,推荐) -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- lombok(可选,简化代码) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
<optional>true</optional>
</dependency>
<!-- 测试依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.application.yml
server:
port: 8080
spring:
redis:
# 从配置文件读取的 Redis 服务器 IP(核心配置)
host: 192.168.1.14 # 替换成你的 Redis 服务器 IP
port: 6379 # Redis 端口,默认6379
password: "abc123" # Redis 密码(无密码则留空)
database: 0 # 选择的数据库编号,默认0
timeout: 10000 # 连接超时时间(毫秒)
# Lettuce 连接池配置(基于 GenericObjectPoolConfig)
lettuce:
pool:
max-active: 8 # 最大连接数
max-idle: 8 # 最大空闲连接数
min-idle: 0 # 最小空闲连接数
max-wait: -1 # 最大等待时间(-1 表示无限制)
# 必加:打印配置加载日志,确认配置是否被读取
logging:
level:
org.springframework.boot.autoconfigure.data.redis: DEBUG
com.example.redis.config: DEBUG
3.RedisConfig.java
package org.hxl.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// JSON序列化配置
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// String 序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key 采用 String 的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash 的 key 也采用 String 的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value 序列化方式采用 jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash 的 value 序列化方式采用 jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
4.RedisController.java
package org.hxl.controller;
import org.hxl.entity.User;
import org.hxl.service.RedisService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/redis")
@RequiredArgsConstructor
public class RedisController {
private final RedisService redisService;
// 设置缓存
@PostMapping("/set")
public String set(@RequestParam String key, @RequestParam String value) {
redisService.set(key, value);
return "设置成功:key=" + key + ", value=" + value;
}
// 设置缓存(带过期时间)
@PostMapping("/set/expire")
public String setWithExpire(@RequestParam String key, @RequestParam String value,
@RequestParam long timeout) {
redisService.set(key, value, timeout, TimeUnit.SECONDS);
return "设置成功(过期时间" + timeout + "秒):key=" + key + ", value=" + value;
}
// 获取缓存
@GetMapping("/get")
public Object get(@RequestParam String key) {
Object value = redisService.get(key);
return value == null ? "key=" + key + " 不存在" : "获取成功:key=" + key + ", value=" + value;
}
// 删除缓存
@DeleteMapping("/delete")
public String delete(@RequestParam String key) {
Boolean result = redisService.delete(key);
return result ? "删除成功:key=" + key : "删除失败(key不存在):key=" + key;
}
// 判断key是否存在
@GetMapping("/hasKey")
public String hasKey(@RequestParam String key) {
Boolean result = redisService.hasKey(key);
return "key=" + key + (result ? " 存在" : " 不存在");
}
//=========================对象操作==============================
// 1. 存储用户对象(中文测试)
@PostMapping("/user/set")
public String setUser() {
// 创建带中文的 User 对象
User user = new User(1L, "张三", 25, "北京市朝阳区");
// 存储对象,key 设计规范:业务名:id
redisService.setObject("user:1", user);
// 也可以存储带过期时间的对象(比如 5 分钟过期)
// redisService.setObject("user:1", user, 5, TimeUnit.MINUTES);
return "用户对象存储成功:" + user;
}
// 2. 获取用户对象
@GetMapping("/user/get")
public User getUser() {
// 读取对象并指定类型为 User.class
return redisService.getObject("user:1", User.class);
}
// 3. 删除用户对象
@DeleteMapping("/user/delete")
public String deleteUser() {
Boolean result = redisService.deleteObject("user:1");
return result ? "用户对象删除成功" : "用户对象不存在";
}
}
5.User.java
package org.hxl.controller;
import org.hxl.entity.User;
import org.hxl.service.RedisService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/redis")
@RequiredArgsConstructor
public class RedisController {
private final RedisService redisService;
// 设置缓存
@PostMapping("/set")
public String set(@RequestParam String key, @RequestParam String value) {
redisService.set(key, value);
return "设置成功:key=" + key + ", value=" + value;
}
// 设置缓存(带过期时间)
@PostMapping("/set/expire")
public String setWithExpire(@RequestParam String key, @RequestParam String value,
@RequestParam long timeout) {
redisService.set(key, value, timeout, TimeUnit.SECONDS);
return "设置成功(过期时间" + timeout + "秒):key=" + key + ", value=" + value;
}
// 获取缓存
@GetMapping("/get")
public Object get(@RequestParam String key) {
Object value = redisService.get(key);
return value == null ? "key=" + key + " 不存在" : "获取成功:key=" + key + ", value=" + value;
}
// 删除缓存
@DeleteMapping("/delete")
public String delete(@RequestParam String key) {
Boolean result = redisService.delete(key);
return result ? "删除成功:key=" + key : "删除失败(key不存在):key=" + key;
}
// 判断key是否存在
@GetMapping("/hasKey")
public String hasKey(@RequestParam String key) {
Boolean result = redisService.hasKey(key);
return "key=" + key + (result ? " 存在" : " 不存在");
}
//=========================对象操作==============================
// 1. 存储用户对象(中文测试)
@PostMapping("/user/set")
public String setUser() {
// 创建带中文的 User 对象
User user = new User(1L, "张三", 25, "北京市朝阳区");
// 存储对象,key 设计规范:业务名:id
redisService.setObject("user:1", user);
// 也可以存储带过期时间的对象(比如 5 分钟过期)
// redisService.setObject("user:1", user, 5, TimeUnit.MINUTES);
return "用户对象存储成功:" + user;
}
// 2. 获取用户对象
@GetMapping("/user/get")
public User getUser() {
// 读取对象并指定类型为 User.class
return redisService.getObject("user:1", User.class);
}
// 3. 删除用户对象
@DeleteMapping("/user/delete")
public String deleteUser() {
Boolean result = redisService.deleteObject("user:1");
return result ? "用户对象删除成功" : "用户对象不存在";
}
}
6.RedisService.java
package org.hxl.service;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
@RequiredArgsConstructor
public class RedisService {
private final RedisTemplate<String, Object> redisTemplate;
// ========== 基本操作 ==========
/**
* 设置缓存
* @param key 键
* @param value 值
*/
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* 设置缓存(带过期时间)
* @param key 键
* @param value 值
* @param timeout 过期时间
* @param unit 时间单位
*/
public void set(String key, Object value, long timeout, TimeUnit unit) {
redisTemplate.opsForValue().set(key, value, timeout, unit);
}
/**
* 获取缓存
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 删除缓存
* @param key 键
* @return 是否删除成功
*/
public Boolean delete(String key) {
return key == null ? false : redisTemplate.delete(key);
}
/**
* 判断key是否存在
* @param key 键
* @return 是否存在
*/
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* 设置过期时间
* @param key 键
* @param timeout 过期时间
* @param unit 时间单位
* @return 是否设置成功
*/
public Boolean expire(String key, long timeout, TimeUnit unit) {
return key == null ? false : redisTemplate.expire(key, timeout, unit);
}
// ================================== 对象专属操作(新增) ================================
/**
* 存储对象(自动序列化为 JSON)
* @param key 键(比如 "user:1")
* @param obj 任意对象(User/Order 等)
*/
public <T> void setObject(String key, T obj) {
redisTemplate.opsForValue().set(key, obj);
}
/**
* 存储对象(带过期时间)
* @param key 键
* @param obj 对象
* @param timeout 过期时间
* @param unit 时间单位
*/
public <T> void setObject(String key, T obj, long timeout, TimeUnit unit) {
redisTemplate.opsForValue().set(key, obj, timeout, unit);
}
/**
* 获取对象(自动反序列化为原对象类型)
* @param key 键
* @param clazz 对象的类类型(比如 User.class)
* @return 原类型对象
*/
@SuppressWarnings("unchecked")
public <T> T getObject(String key, Class<T> clazz) {
Object value = redisTemplate.opsForValue().get(key);
return value == null ? null : (T) value;
}
/**
* 删除对象
* @param key 键
* @return 是否删除成功
*/
public Boolean deleteObject(String key) {
return redisTemplate.delete(key);
}
}
7.App.java
package org.hxl;
/**
* Hello world!
*
*/
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App
{
public static void main(String[] args) {
SpringApplication.run(App.class, args);
System.out.println("===== Spring Boot 启动成功 =====");
}
}
8.接口调用
http://localhost:8080/redis/user/set
接口获取数据
http://localhost:8080/redis/user/get
登录Redis查看
[root@localhost conf]# /usr/local/services/redis/bin/redis-cli -c -h 192.168.1.14 -p 6379 -a abc123 --raw
Warning: Using a password with '-a' option on the command line interface may not be safe.
192.168.1.14:6379> get user:1
["org.hxl.entity.User",{"id":1,"name":"张三","age":25,"email":"北京市朝阳区"}]