缓存对减轻服务器压力至关重要,这一篇简单记录一下。
缓存这一块,主要用到了这4个注解:@EnableCaching, @Cacheable,@CachePut,@CacheEvict 。
其中@EnableCaching告诉Spring框架开启缓存能力,@Cacheable来配置访问路径是否缓存,@CachePut来更新缓存,@CacheEvict来清理缓存,具体用法看下面的代码。
1.开启Spring的缓存功能java
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication @EnableCaching//开启缓存 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
2.对访问路径(URL)配置缓存信息web
@GetMapping("/{id}") @Cacheable("users")//设置缓存用户信息,缓存的名称为users public User getUserInfo(@PathVariable int id) { User user = new User(); user.setId(id); int random=new Random().nextInt(999); user.setName("user " + random); System.out.println("random is "+random); return user; }
3.更新缓存信息spring
@PostMapping("/update") @CachePut(value ="users",key = "#user.getId()")//更新指定的用户缓存信息 public boolean updateUserInfo( User user){ System.out.println("updateUserInfo "+user.toString()); return true; }
4.清除缓存信息缓存
@PostMapping("/remove") @CacheEvict(value = "users",key = "#user.getId()")//清除指定的用户缓存信息 public boolean removeUserInfoCache(@RequestBody User user){ System.out.println("removeUserInfoCache "+user.toString()); return true; } @PostMapping("/remove/all") @CacheEvict(value = "users",allEntries = true)//清除全部的用户缓存信息 public boolean removeAllUserInfoCache(){ System.out.println("removeAllUserInfoCache "); return true; }
下面放一个完整的缓存类demo服务器
package com.spring.cache; import com.spring.beans.User; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.web.bind.annotation.*; import java.util.Random; /** * Created by zhangyi on 2017/4/13. * * 缓存demo * */ @RestController @RequestMapping("/cache/user") public class CacheController { @GetMapping("/{id}") @Cacheable("users")//设置缓存用户信息,缓存的名称为users public User getUserInfo(@PathVariable int id) { User user = new User(); user.setId(id); int random=new Random().nextInt(999); user.setName("user " + random); System.out.println("random is "+random); return user; } @PostMapping("/update") @CachePut(value ="users",key = "#user.getId()")//更新指定的用户缓存信息 public boolean updateUserInfo( User user){ System.out.println("updateUserInfo "+user.toString()); return true; } @PostMapping("/remove") @CacheEvict(value = "users",key = "#user.getId()")//清除指定的用户缓存信息 public boolean removeUserInfoCache(@RequestBody User user){ System.out.println("removeUserInfoCache "+user.toString()); return true; } @PostMapping("/remove/all") @CacheEvict(value = "users",allEntries = true)//清除全部的用户缓存信息 public boolean removeAllUserInfoCache(){ System.out.println("removeAllUserInfoCache "); return true; } }