小言_互联网的博客

SpringBoot使用缓存

324人阅读  评论(0)

SpringBoot使用缓存

  • SpringBoot来简单整合缓存,
  1. 项目,pom文件中加入spring-boot-starter-cache依赖
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
            <version>2.1.7.RELEASE</version>
        </dependency>
  1. 实体类
@Data
public class User {
    private Long id;

    private String username;

    private String password;

    private Date createTime;

    private Date updateTime;
}
  1. 启动类上加入@EnableCaching开启缓存
@SpringBootApplication
//开启缓存
@EnableCaching
public class SpringbootCacheApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootCacheApplication.class, args);
	}
}
  1. 使用Controller做测试
/**
 * @Description
 * @Author 
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2019-09-24
 */
@RestController
public class CacheUserController {
    @Autowired
    private UserService userService;
    //http://localhost:8787/saveUser?id=2&username=关小羽
    @ApiOperation(value = "数据缓存Cache", httpMethod = "GET")
    @GetMapping("/saveUser")
    @CachePut(value = "user" ,key = "#id")
    public User saveUser(Long id,String username){
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        userService.save(user);
        return user;
    }
    //http://localhost:8787/queryUser?id=2
    @GetMapping("/queryUser")
    @Cacheable(value = "user" , key = "#id")
    public User queryUser(Long id){
        User user = userService.queryUser(id);
        System.out.println (user);
        return user;
    }
    //http://localhost:8787/deleteUser?id=2
    @GetMapping("/deleteUser")
    @CacheEvict(value = "user", key = "#id")
    public String deleteUser(Long id){
        userService.delete(id);
        System.out.println ("success");
        return "success";
    }
    //http://localhost:8787/deleteCache
    @GetMapping("/deleteCache")
    @CacheEvict(value = "user", allEntries = true)
    public void deleteCache() {

    }
}

转载:https://blog.csdn.net/weixin_43854141/article/details/101378484
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场