二、配置连接redis的application.yml文件4.0.0 org.springframework.boot spring-boot-starter-parent2.7.1 cn.tedu redisdemo0.0.1-SNAPSHOT redisdemo Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-testtest org.springframework.boot spring-boot-starter-data-redisorg.projectlombok lombok1.18.10 compile org.springframework.boot spring-boot-maven-plugin
spring:
redis:
host: 127.0.0.1
port: 6379
server:
port: 8083
三、启动redis并连接
3.1 进入到安装redis的目录下
3.2 使用命令启动并去连接
四、测试连接:做一个基本的连接测试package cn.tedu.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/redis")
public class RedisController {
@Autowired
private StringRedisTemplate template;
@GetMapping("/hello")
public String hello(String name,String age){
template.opsForValue().set(name,age);
String value = template.opsForValue().get(name);
System.out.println(name+","+value);
return name+","+value;
}
}
在浏览器中访问该项目地址,运行效果如下图,说明redis已连接成功,并且获取数据也成功了!http://localhost:8083/redis/hello?name=%E5%B0%8F%E6%9D%8E%E5%A4%B4&age=23
五、通过对象的方式来进行数据的保存与读取。在项目中新增一个User类package cn.tedu.pojo;
import lombok.Data;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
public class User {
private String name;
private Integer age;
private String Gender;
}
测试代码如下图:
@GetMapping("/user")
public String getUser(){
List userList = new ArrayList<>();
userList.add(new User().setName("小李头").setAge(23).setGender("女"));
userList.add(new User().setName("小白").setAge(20).setGender("男"));
userList.add(new User().setName("张三").setAge(30).setGender("男"));
userList.add(new User().setName("小法师").setAge(15).setGender("女"));
template.opsForValue().set("user", String.valueOf(userList));
System.out.println(template.opsForValue().get("user"));
return template.opsForValue().get("user");
}
通过访问地址 http://localhost:8083/redis/user ,最后运行效果如下图 :
六、以上内容,本人也是在学习整理,如果有错误或语法不当之处,欢迎批评斧正。感谢!!!



