【SpringBoot学习】23-@Cacheable实现

@Cacheable
在这里插入图片描述
源码分析
在这里插入图片描述
@Cacheable中参数

在这里插入图片描述

配置类略

依赖导入

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

启动类

使用@EnableCaching 开启缓存

@EnableCaching //开启注解 缓存
@SpringBootApplication
@MapperScan("cn.qqqking.springboot.mapper")
public class SpringBoot13CacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBoot13CacheApplication.class, args);
    }

}

Mapper

/**
 * @author AnQi
 * @date 2020/3/15 10 46:34
 * @description
 */
public interface UserMapper {
    @Select("select * from user where id = #{id}")
    User getUserById(Integer id);
}

service层

方法前使用 @Cacheable(cacheNames = “user”,key = “#id”)

  • cacheNames 缓存容器名字
  • key 缓存容器中key
  • value return user;
/**
 * @author AnQi
 * @date 2020/3/15 10 57:15
 * @description
 */
@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    /**
     * cacheNames 缓存容器名字
     * key 缓存容器中key
     * value return user;
     * @param id
     * @return
     */
    @Cacheable(cacheNames = "user",key = "#id")
    public User getUserById(Integer id){
        User user = userMapper.getUserById(id);
        return user;
    }
}

controller层

/**
 * @author AnQi
 * @date 2020/3/15 10 58:45
 * @description
 */
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") Integer id){
        User user = userService.getUserById(id);
        return user;
    }
}
发布了130 篇原创文章 · 获赞 8 · 访问量 2849

猜你喜欢

转载自blog.csdn.net/ange2000561/article/details/104875407