1.配置链接Redis
application.properties
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码,默认为空
spring.redis.password=
# 连接超时时间(毫秒)
spring.redis.timeout=5000
2.传入单个值
/**
* @author kismet
* @date 2020/8/11 10:13 上午
*/
@RestController
public class RedisController {
@Resource
private StringRedisTemplate stringRedisTemplate;
@PostMapping("/redis/{key}/{value}")
public Boolean setValue(@PathVariable("key") String key,@PathVariable("value") String value){
boolean flag=true;
try {
stringRedisTemplate.opsForValue().set(key,value);
} catch (Exception e) {
e.printStackTrace();
flag=false;
}
return flag;
}
@GetMapping("/redis/{key}")
private String getValue(@PathVariable("key") String key){
return stringRedisTemplate.opsForValue().get(key);
}
}
3.传入对象
/**
* @author kismet
* @date 2020/8/11 9:50 上午
*/
@RestController
public class UserController {
@Resource
private RedisTemplate redisTemplate;
@Resource
private User user;
@PostMapping("/user/{id}/{name}/{password}")
public void setUser(@PathVariable("id") String id,@PathVariable("name") String name,@PathVariable("password") String password){
user.setId(Integer.parseInt(id));
user.setName(name);
user.setPassword(password);
redisTemplate.opsForValue().set("user",user);
User redisGetUser = (User) redisTemplate.opsForValue().get("user");
System.out.println(redisGetUser);
}
}
/**
* @author kismet
* @date 2020/8/11 9:50 上午
*/
@Component
public class User implements Serializable {
private int id;
private String name;
private String password;
public User() {
}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
4.测试
http://localhost:8080/redis/name/tom
http://localhost:8080/redis/name
http://localhost:8080/user/1/zs/123456