整合redis
org.springframework.boot spring-boot-starter-cache org.springframework.boot spring-boot-starter-data-reis 复制代码
#配置redisspring.redis.host=192.168.243.129spring.redis.port=6379spring.redis.database=0spring.redis.password=bisnow#配置cachespring.cache.cache-names=c1复制代码
@SpringBootApplication@EnableCachingpublic class RediscacheApplication {复制代码
@Service// 配置缓存名称,不是必须的,可以在每一次启动时指定@CacheConfig(cacheNames = "c1")public class UserService { /** * @Cacheable 将当前方法的返回值缓存起来 * 缓存的key就是方法的参数,方法返回值是value * * 如果多个参数,同时作为key(必须都满足才能取出缓存) * 多参数指定某个参数为key 需要手动配置 * @Cacheable(key = "id") 表示只用id作为key * @param id * @return */ @Cacheable(key = "#id") public User getUserById(Long id,String username){ System.out.println(id); User user = new User(); user.setId(id); return user; } /** * 删除 * allEntries 默认为false,表示根据key删除而不是全删除缓存 * beforeInvocation 默认为false 表示先删除数据,后清除缓存 * @param id */ //这个注解一般加在删除方法上,表示同步删除缓存中的数据 @CacheEvict(allEntries = false,beforeInvocation = false) public void deleteById(Long id){ //在这里执行删除操作,去数据库中删除 //正常的逻辑:首先去数据库中删除,然后去缓存中删除 } /** * 更新 * @CachePut 这个注解一般用在修改方法上 * 表示修改数据库数据的同时也修改缓存 * 更新方法必须有返回值 * geng * @param id * @return */ @CachePut public User updateById(Long id){ User user = new User(); user.setId(99L); user.setUsername("李四"); return user; }}复制代码
@RunWith(SpringRunner.class)@SpringBootTestpublic class RediscacheApplicationTests { @Autowired UserService userService; @Test public void test1(){ User userById = userService.getUserById(99L,""); System.out.println("userbyid >>> 1:" +userById); User userById2 = userService.getUserById(99L,""); System.out.println("uuerbyid >>> 2:" + userById2); } @Test public void test2(){ User userById1 = userService.getUserById(99L,""); System.out.println("uuerbyid >>> 1:" + userById1); userService.deleteById(99L); User userById2 = userService.getUserById(99L,""); System.out.println("uuerbyid >>> 2:" + userById2); } @Test public void test3(){ User userById = userService.getUserById(99L,""); System.out.println("userbyid >>> 1:" +userById); userService.updateById(99L); User userById2 = userService.getUserById(99L,""); System.out.println("uuerbyid >>> 2:" + userById2); }}复制代码