pom依赖
< ! -- Spring Data Redis 依赖 -- >
< dependency>
< groupId> org. springframework. boot< / groupId>
< artifactId> spring- boot- starter- data- redis< / artifactId>
< / dependency>
< ! -- commons- pool2 对象池依赖 -- >
< dependency>
< groupId> org. apache. commons< / groupId>
< artifactId> commons- pool2< / artifactId>
< / dependency>
yml
spring :
redis :
# 同于一个数据库
database : 0
host : 127.0 .0 .1
port : 6379
Student 测试实体
@Data
@AllArgsConstructor
public class Student implements Serializable {
private Integer id;
private String name;
private Double score;
@JsonFormat ( pattern = "yyyy-MM-dd" )
private Date birthday;
}
RedisCRUDHandler(redis 对象 常用增删改查)
@RestController
public class RedisCRUDHandler {
@Autowired
private RedisTemplate redisTemplate;
@PostMapping ( "/set" )
public void set ( @RequestBody ( required = false ) Student student) {
Calendar c = Calendar . getInstance ( ) ;
c. set ( 1990 , 2 , 1 ) ;
Date date = c. getTime ( ) ;
student = new Student ( 1 , "张三" , 99.9 , date) ;
redisTemplate. opsForValue ( ) . set ( "student_" , student, 1 , TimeUnit . MINUTES) ;
}
@GetMapping ( "/get/{key}" )
public Student get ( @PathVariable ( "key" ) String key) {
return ( Student ) redisTemplate. opsForValue ( ) . get ( key) ;
}
@DeleteMapping ( "delete/{key}" )
public boolean delete ( @PathVariable ( "key" ) String key) {
Boolean delete = redisTemplate. delete ( key) ;
System . out. println ( "删除:" + delete) ;
return ! redisTemplate. hasKey ( "key" ) ;
}
}
Redis5Type(redis 其他5种 操作)
@RestController
public class Redis5Type {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping ( "/string" )
public String stringTest ( ) {
redisTemplate. opsForValue ( ) . set ( "str" , "hello word" ) ;
return ( String ) redisTemplate. opsForValue ( ) . get ( "str" ) ;
}
@GetMapping ( "/list" )
public List < String > listTest ( ) {
ListOperations < String , String > lo = redisTemplate. opsForList ( ) ;
lo. leftPush ( "list_" , "hello" ) ;
lo. leftPush ( "list_" , "word" ) ;
List < String > list_ = lo. range ( "list_" , 0 , 1 ) ;
return list_;
}
@GetMapping ( "/set" )
public Set < String > setTest ( ) {
SetOperations < String , String > so = redisTemplate. opsForSet ( ) ;
so. add ( "set_" , "hello1" , "hello2" ) ;
so. add ( "set_" , "word" ) ;
Set < String > set_ = so. members ( "set_" ) ;
return set_;
}
@GetMapping ( "/zset" )
public Set < String > zsetTest ( ) {
ZSetOperations < String , String > zso = redisTemplate. opsForZSet ( ) ;
zso. add ( "zset_" , "hello" , 1 ) ;
zso. add ( "zset_" , "word" , 2 ) ;
Set < String > zset_ = zso. range ( "zset_" , 0 , 1 ) ;
return zset_;
}
@GetMapping ( "/hash" )
public String hashTest ( ) {
HashOperations < String , String , String > ho = redisTemplate. opsForHash ( ) ;
ho. put ( "key" , "hashkey" , "hash-hello-word" ) ;
String s = ho. get ( "key" , "hashkey" ) ;
return s;
}
}