Spring boot创建第一级和第二级缓存

时间:2017-11-29 11:09:35

标签: jpa caching spring-boot time second-level-cache

Spring Boot with JPA and Rest我想  •创建第一级和第二级缓存。第一级缓存将最后5分钟的数据存储在内存中,而第二级缓存将整个数据库保存在缓存中(考虑到数据集很小)。

和 •在第一级缓存中搜索数据(如果找到),从其返回数据,否则从第二级缓存中搜索。它应该存在于二级缓存中。

请帮我解决。

这是我的控制器类:

    @RestController
    @RequestMapping("/rest")
    @CacheConfig(cacheNames = "EmployeesCache")
    public class EmployeeController {

        @Autowired
        EmployeesRepository employeesRepository;

        @Autowired
        AddressRepository addressRepository;
        @RequestMapping(value = "/dummyEmployees/", me

thod = RequestMethod.GET)
    public ResponseEntity<List<Employee>> listdummydata() {
        List<Employee> employees = EmployeesRepository.populateDummyEmployees();

        return new ResponseEntity<List<Employee>>(employees, HttpStatus.OK);
    }
  -------------------Create an Employee----------------------------------------
    @CachePut(cacheNames="EmployeesCache")
    @PostMapping("/newEmployee/")
    public ResponseEntity<?> createEmployee(@RequestBody Employee emp, UriComponentsBuilder ucBuilder)
    {

        employeesRepository.save(emp);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/rest/{id}").buildAndExpand(emp.getId()).toUri());
        return new ResponseEntity<String>(headers, HttpStatus.CREATED);
    }

 // -------------------add Address-------------------------------------------
    @CachePut(cacheNames="EmployeesCache")
    @PostMapping("/addAddressToEmployee/{employee_id}")
    public void addAddress(@RequestBody Address address,@PathVariable("employee_id") int employee_id)
    {   Employee emp= new Employee(employee_id,"");
        address.setEmployee(emp);

        addressRepository.save(address);

    }

     // -------------------get Address based in id of address-------------------------------------------    
    @Cacheable()
    @GetMapping("/addressid/{id}")
    public Address getaddress(@PathVariable("id") final Integer id) {
        return addressRepository.findOne(id);
    }


 // -------------------get all employees------------------------------------------- 

    @GetMapping("/all/")
    public ResponseEntity<List<Employee>> getAll() {
        List<Employee> employees = employeesRepository.findAll();
        if(employees.isEmpty())
            throw new CustomNotFoundException("Emply table");
        return new ResponseEntity<List<Employee>>(employees, HttpStatus.OK);
    }
 // -------------------get employee by id-------------------------------------------    
    @Cacheable()
    @GetMapping("/id/{id}")
    public Employee getId(@PathVariable("id") final Integer id) {
        Employee emp= employeesRepository.findOne(id);
        if(emp== null)
            throw new CustomNotFoundException("Not found employee with id " + id);
        return emp;
    }

 // -------------------get employee by name-------------------------------------------  
    @Cacheable()
    @GetMapping("/name/{name}")
    public List<Employee> getEmployeeByName(@PathVariable("name") final String name) {
        List<Employee> employees= employeesRepository.findByName(name);
        if(employees.isEmpty())
            throw new CustomNotFoundException("Not found employee with name " + name);
        return employees;
    }

 // -------------------get employee by pin code-------------------------------------------  
    @Cacheable()
    @GetMapping("/pincode/{pincode}")
    public List<Employee> getPincode(@PathVariable("pincode") final String pincode) {
        List<Employee> employees= employeesRepository.findEmployeeByPincode(pincode);
        if(employees.isEmpty())
            throw new CustomNotFoundException("Not found employee with pincode " + pincode);
        return employees;
    }

 // -------------------get employee by city ------------------------------------------- 
    @Cacheable()
    @GetMapping("/city/{city}")
    public List<Employee> getCity(@PathVariable("city") final String city) {

        List<Employee> employees= employeesRepository.findEmployeeByCity(city);
        if(employees.isEmpty())
            throw new CustomNotFoundException("Not found employee with city " + city);
        return employees;
    }

}

这是ehcache.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd"
         updateCheck="true"
         monitoring="autodetect"
         dynamicConfig="true">
<diskStore path="java.io.tmpdir" />

    <cache name="EmployeesCache"
           maxElementsInMemory="100"
           eternal="false"
           overflowToDisk="false"
           timeToLiveSeconds="300"
           timeToIdleSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
    </cache>


</ehcache>

这是应用程序文件:

spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username =root
spring.datasource.password =root

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect


spring.cache.ehcache.config=classpath:ehcache.xml
spring.cache.ehcache.provider=net.sf.ehcache.CacheManager

这是我的服务类:

@CacheConfig(cacheNames = "EmployeesCache")
public interface EmployeesRepository extends JpaRepository<Employee, Integer> {
    List<Employee> findByName(String name);

    @CacheEvict(allEntries = true)
    public static void clearCache(){}



    @Query("SELECT e FROM Employee e join e.AddressList a WHERE a.pincode =:pincode")
    public List<Employee> findEmployeeByPincode(@Param("pincode") String pincode);



    @Query("SELECT e FROM Employee e join e.AddressList a WHERE a.city =:city")
    public List<Employee> findEmployeeByCity(@Param("city") String city);

    static List<Employee> populateDummyEmployees(){
        List<Employee> employees = new ArrayList<Employee>();
        employees.add(new Employee(1,"Sam"));
        employees.add(new Employee(2,"Tom"));
        employees.add(new Employee(3,"Jim"));
        employees.add(new Employee(4,"Git"));
        return employees;
    }

}

这是我的配置类:

@EnableCaching
@EnableJpaRepositories(basePackages = "com.spring.jpa.service")
@SpringBootApplication
public class SpringJpaHibernateExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringJpaHibernateExampleApplication.class, args);
    }
    @Bean
    public EhCacheCacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheCacheManager().getObject());
    }

    @Bean
    public EhCacheManagerFactoryBean ehCacheCacheManager() {
        EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
        cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
        cmfb.setShared(true);
        return cmfb;
    }


}

请帮助进一步继续

0 个答案:

没有答案