JAVA-springboot 整合Redis
SpringBoot从入门到精通-第16章 Redis
一、Redis简介
二、整合Redis
-
2.1、创建springboot项目
-
2.2、引入Redis依赖
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.5.3</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>_20250704springboot_redis</artifactId><version>0.0.1-SNAPSHOT</version><name>20250704springboot_redis</name><description>20250704springboot_redis</description><url/><licenses><license/></licenses><developers><developer/></developers><scm><connection/><developerConnection/><tag/><url/></scm><properties><java.version>17</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-redis</artifactId><version>1.4.7.RELEASE</version></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></plugin></plugins></build></project>
- 2.3、添加配置文件
spring.application.name=20250704springboot_redis
spring.data.redis.host=10.0.0.132
spring.data.redis.port=6379
- 2.4、编写代码使用Redis
package com.example._20250704springboot_redis;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class Controller {@Autowiredprivate StringRedisTemplate template;@RequestMapping("/redis")
// public String sout(){
// System.out.println("redis_fun");
// return "redis";
// }public String set(){template.opsForValue().set("name","zhang3");return "set over";}@RequestMapping("/getredis")public String get(){return template.opsForValue().get("name");}
}
- 2.5、测试Redis,增、查