使用@Cacheable时如何读取Redis缓存?

时间:2018-12-07 14:50:28

标签: spring redis spring-data-redis

我正在使用@Cacheable开发 Spring Boot + Redis 示例。我已经开发了一个REST端点,该端点可以按预期缓存数据,但是我对数据正存储在Redis中并不感到好奇。

有人可以指导

  

1)数据如何保存

     

2)如何从Redis读取可缓存密钥的数据?

127.0.0.1:6379> KEYS *
1) "post-top::SimpleKey []"

Author.java

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Author implements Serializable{
    private static final long serialVersionUID = 1L;
    private String name;
}

enter image description here

Post.java

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Post implements Serializable{
    private static final long serialVersionUID = 1L;

    private String id;
    private String title;
    private String description;
    private String image;
    private int shares;
    private Author author;
}

PostController.java

@RestController
@RequestMapping("/posts")
public class PostController {
    private static final Logger log = LoggerFactory.getLogger(PostController.class);

    @Autowired
    private PostService postService;

    @Cacheable(value = "post-single", key="#id", unless = "#result.shares < 500")
    @GetMapping("/{id}")
    public Post getPostByID(@PathVariable String id) throws PostNotFoundException {
        log.info("get post with id {}", id);
        return postService.getPostByID(id);
    }


    @CachePut(value = "post-single", key = "#post.id")
    @PutMapping("/update")
    public Post updatePostByID(@RequestBody Post post) throws PostNotFoundException {
        log.info("update post with id {}", post.getId());
        postService.updatePost(post);
        return post;
    }


    @CacheEvict(value = "post-single", key = "#id")
    @DeleteMapping("/delete/{id}")
    public void deletePostByID(@PathVariable String id) throws PostNotFoundException {
        log.info("delete post with id {}", id);
        postService.deletePost(id);
    }

    @Cacheable(value = "post-top")
    @GetMapping("/top")
    public List<Post> getTopPosts() {
        return postService.getTopPosts();
    }

    @CacheEvict(value = "post-top")
    @GetMapping("/top/evict")
    public void evictTopPosts() {
        log.info("Evict post-top");
    }
}

0 个答案:

没有答案
相关问题