springbootJava基础springboot进阶

SpringBoot缓存注解介绍+实战

2020-03-17  本文已影响0人  HeloWxl

声明

1、介绍SpringBoot注解

1.1 @Cacheable

1.1.1 Cacheable属性

//自定义配置类配置keyGenerator
@Configuration
public class MyCacheConfig {
    @Bean("myKeyGenerator")
    public KeyGenerator keyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                return method.getName()+"["+ Arrays.asList(params).toString() +"]";
            }
        };
    }
}
@Cacheable(cacheNames = "user",keyGenerator = "myKeyGenerator")
    public User getUser(Integer id) {
        System.out.println("查询" + id + "号用户");
        User user = userMapper.getUserId(id);
        return user;
    }

1.2 @CachePut

@CachePut(value="user",key = "#result.id")
    public User updateUser(User user){
        System.out.println("updateUser:"+user);
        userMapper.updateUser(user);
        return user;
    }

1.3 @CacheEvict 清除缓存

@CacheEvict(value = "user",key = "#id")
    public void deleteUser(Integer id){
        System.out.println("deleteUser:"+id);
        userMapper.deleteUserById(id);
    }

1.4 @Caching

@Caching(
            cacheable = {
                    @Cacheable()
            },
            put = {
                    @CachePut(),
                    @CachePut()
            },
            evict = {
                    @CacheEvict()
            }
    )
    public 返回值 方法名(参数类型 参数){
        return 返回结果;
    }

1.5 @EnableCaching


1.6 @CacheConfig


2、缓存实战

2.1 项目搭建

搭建一个SpringBoot+Mybatis环境,这个就不多说了。


项目结构.png

2.2 pom.xml

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

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

2.3 Dao层

@Mapper
public interface ArtileDao {
   
    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    Artile queryById(Integer id);

    /**
     * 新增数据
     *
     * @param artile 实例对象
     * @return 影响行数
     */
    int insert(Artile artile);

    /**
     * 修改数据
     *
     * @param artile 实例对象
     * @return 影响行数
     */
    int update(Artile artile);

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 影响行数
     */
    int deleteById(Integer id);

}

2.4 ServiceImpl层

@Service("artileService")
@CacheConfig(cacheNames = "articleCache")
public class ArtileServiceImpl implements ArtileService {
    @Resource
    private ArtileDao artileDao;

    /**
    * @Description: 根据主键查询
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:57 AM
    */ 
    @Cacheable(value = "articleCache")
    @Override
    public Artile queryById(int id) {
        try {
            //模拟耗时操作
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return this.artileDao.queryById(id);
    }

    /**
    * @Description: 新增数据
    * @params: [artile]
    * @return: int
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:57 AM
    */ 
    @CachePut
    @Override
    public int insert(Artile artile) {
        return this.artileDao.insert(artile);
    }

    /**
    * @Description: 修改数据
    * @params: [artile]
    * @return: com.ustcinfo.cache.entity.Artile
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:57 AM
    */ 
    @CacheEvict(key = "#artile.id")
    @Override
    public int update(Artile artile) {
        return  this.artileDao.update(artile);
    }

    /**
    * @Description: 根据主键删除
    * @params: [id]
    * @return: boolean
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:58 AM
    */ 
    @CacheEvict(key = "#id")
    @Override
    public boolean deleteById(Integer id) {
        return this.artileDao.deleteById(id) > 0;
    }
}

2.5 Controller层

@RestController
@RequestMapping("artile")
public class ArtileController {
    /**
     * 服务对象
     */
    @Resource
    private ArtileService artileService;
    
  /**
    * @Description: 根据主键查询
    * @params: [id]
    * @return: java.util.Map<java.lang.String,java.lang.Object>
    * @Author: wangxianlin
    * @Date: 2020/3/17 1:48 PM
    */ 
    @GetMapping("queryById")
    public Map<String,Object> queryById(@RequestParam("id") int id) {
        Map<String,Object> map = new HashMap<>();
        Long start = System.currentTimeMillis();
        map.put("data",this.artileService.queryById(id));
        Long end = System.currentTimeMillis();
        map.put("time",(end-start));
        return map;
    }

    /**
    * @Description: 新增
    * @params: [artile]
    * @return: int
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:55 AM
    */
    @PostMapping("insert")
    public int insert(@RequestBody Artile artile) {
        return this.artileService.insert(artile);
    }

    /**
    * @Description: 修改
    * @params: [artile]
    * @return: com.ustcinfo.cache.entity.Artile
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:55 AM
    */
    @PostMapping("update")
    public int update(@RequestBody Artile artile) {
        return this.artileService.update(artile);
    }

    /**
    * @Description: 根据主键删除
    * @params: [id]
    * @return: boolean
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:56 AM
    */
    @GetMapping("deleteById")
    public boolean deleteById(@RequestParam("id") Integer id) {
        return this.artileService.deleteById(id);
    }
}

2.6 启动类

@MapperScan("com.ustcinfo.cache.dao")
@SpringBootApplication
//开启缓存注解驱动,否则后面使用的缓存都是无效的
@EnableCaching
public class CacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class, args);
    }
}

3、postman测试

3.1 根据主键查询

3.2 添加

image.png

3.3 修改

image.png

3.3 删除

image.png
上一篇 下一篇

猜你喜欢

热点阅读