您的位置:首页 > 编程语言 > Java开发

Spring Cache与JPA的简单使用

2020-06-28 05:08 417 查看

依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

application.yml

spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/spring_boot?serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver

jpa:
database: mysql
hibernate:
ddl-auto: update
show-sql: true

Cache注解

  • @EnableCaching:开启基于注解的缓存

  • @CachePut:更新缓存

  • @CacheEvict:清空缓存

    value:缓存组件名
  • key:清空指定的缓存
  • allEntries = true:清除这个指定缓存组件中的所有数据
  • beforeInvocation = false:缓存的清除是否再方法之前执行;默认方法之后执行
  • @Cacheable

      不能使用result 原因:运行前就需要key
  • cachenames/value:指定缓存组件名字
  • key:缓存数据使用的key;不写,默认方法参数值
      可写SpEL表达式
  • keyGenerator:指定key的生成器;
  • condition:指定符合条件缓存
  • unless:指定符合条件不缓存;可对结果进行判断;如:unless="#result==null"
  • sync:是否开启异步模式
  • @Caching:定义复杂的缓存规则

  • 如:

    @Caching(
    cacheable = {
    @Cacheable(value = "user", key = "#id")
    },
    put = {
    @Cacheput(value = "user", key = "#result.id"),
    @CachePut(value = "user", key = "#result.username")
    }
    )
  • @Cacheconfig

      抽取公共的cache属性
    • cacheNames 也就是 value
    • cacheResolver
    • keyGenerator
    • cacheManager

    开启基于注解缓存

    • 启动类加上 @EnableCaching
    package com.live;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cache.annotation.EnableCaching;
    
    @SpringBootApplication
    @EnableCaching
    public class CacheApplication {
    
    public static void main(String[] args) {
    SpringApplication.run(CacheApplication.class, args);
    }
    
    }

    Model

    package com.live.model;
    
    import lombok.Data;
    import javax.persistence.*;
    
    @Entity
    @Data
    @Table(name = "cache_user")
    public class CacheUser {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    
    @Column(name = "cache_username", length = 100, unique = true)
    private String username;
    
    @Column(name = "cache_password", length = 125)
    private String password;
    
    }

    Repository

    package com.live.repository;
    
    import com.live.model.CacheUser;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface CacheUserRepository extends JpaRepository<CacheUser, Integer> {
    
    CacheUser findByUsername(String username);
    
    CacheUser findOneById(Integer id);
    
    }

    Controller

    package com.live.controller;
    
    import com.live.model.CacheUser;
    import com.live.repository.CacheUserRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cache.annotation.CacheConfig;
    import org.springframework.cache.annotation.CacheEvict;
    import org.springframework.cache.annotation.CachePut;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    @RestController
    @CacheConfig(cacheNames = "user")
    public class CacheUserController {
    
    @Autowired
    private CacheUserRepository cacheUserRepository;
    
    @GetMapping("/findOne/{id}")
    @Cacheable(key = "#id")
    public CacheUser findByName(@PathVariable(value = "id") Integer id) {
    System.out.println("查询ID:" + id);
    return cacheUserRepository.findOneById(id);
    }
    
    @GetMapping("/findOneByName/{name}")
    @Cacheable(keyGenerator = "myKeyGenerator")
    public CacheUser findByName(@PathVariable(value = "name") String name) {
    System.out.println("查询Name:" + name);
    return cacheUserRepository.findByUsername(name);
    }
    
    @GetMapping("/findAll")
    @Cacheable(keyGenerator = "myKeyGenerator")
    public List<CacheUser> findAll() {
    return cacheUserRepository.findAll();
    }
    
    @GetMapping("/update/{id}/{username}")
    @CachePut(key = "#id")
    public CacheUser updateById(@PathVariable(value = "username") String username, @PathVariable(value = "id") Integer id) {
    CacheUser update = cacheUserRepository.findOneById(id);
    update.setUsername(username);
    return cacheUserRepository.save(update);
    }
    
    @GetMapping("/clearCacheAll")
    @CacheEvict(allEntries = true)
    public String clearCacheAll() {
    return "SUCCESS!";
    }
    
    @GetMapping("/clearCacheById/{id}")
    @CacheEvict(key = "#id")
    public String clearCacheById(@PathVariable(value = "id") Integer id) {
    return "SUCCESS!";
    }
    
    }

    自定义KeyGenerator

    package com.live.config;
    
    import org.springframework.cache.interceptor.KeyGenerator;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import java.util.Arrays;
    import java.util.List;
    
    @Configuration
    public class MyCacheKeyGenerator {
    
    @Bean(name = "myKeyGenerator")
    public KeyGenerator keyGenerator() {
    return (o, method, objects) -> {
    String key;
    List<Object> args = Arrays.asList(objects);
    if (args.size() > 0) {
    key = method.getName() + "_" + args;
    } else {
    key = method.getName();
    }
    System.out.println(s);
    return key;
    };
    }
    
    }
  • 内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: