springboot整合redis的使用,SpringBoot中如何操作Redis
一、先创建springboot项目,然后添加相关POM依赖
<!--集成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>
二、配置连接redis的application.yml文件
spring:
redis:
host: 127.0.0.1
port: 6379
server:
port: 8083
//连接池
spring.redis.lettuce.pool.min-idle=5
spring.redis.lettuce.pool.max-idle=10
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=1ms
spring.redis.lettuce.shutdown-timeout=100ms
三、启动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;
/**
* @Classname RedisController
*/
@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;
}
}
五、通过对象的方式来进行数据的保存与读取。在项目中新增一个User类
package cn.tedu.pojo;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* @Classname User
*/
@Data
@Accessors(chain = true)
public class User {
private String name;
private Integer age;
private String Gender;
}
@GetMapping("/user")
public String getUser(){
List<User> 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");
}
还没有评论,来说两句吧...