網頁

2020/7/19

Spring Boot Caching simple ConcurrentHashMap 範例

Spring Boot Caching(快取)使用預設的ConcurrentHashMap快取範例。


注意不要在生產環境使用Spring Boot Cache預設的ConcurrentHashMap,因為其生命週期為應用程式的執行期間,且Spring Boot Cache沒提供存活時間及最大空間等設定,因此若用在生產環境可能會造成記憶體洩漏


範例環境:

  • Spring Boot版本2.2.1.RELEASE
  • Maven
  • Lombok

建立Spring Boot專案(參考IntelliJ IDEAEclipse STS)。

spring-boot-starter-cache依賴引入專案。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.abc</groupId>
    <artifactId>spring-boot-cache-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-cache-demo</name>
    <description>Spring Boot Caching Demo</description>
    <packaging>jar</packaging>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId> <!-- 引入Spring Boot Cache -->
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

專案的application.properites設定。spring.cache.cache-names用來設定快取的名稱。若有多個快取用逗號分隔,例如spring.cache.cache-names=employee_cache,department_cache

#context path
server.servlet.context-path=/demo
#port
server.port=8080

#cache
spring.cache.cache-names=employee_cache

一旦設定了快取名稱,則在使用annotation如@Cacheable時必須指定名稱,否則執行期間方法被呼叫時會拋出java.lang.IllegalStateException: No cache could be resolved for 'Builder[...]錯誤。

Spring Boot Cache僅提供抽象的annotation來設定及操作快取。若未設定快取的實作(cache provider),則預設以ConcurrentHashMap實現快取效果。

@Configuration類別名稱前加上@EnableCaching才能啟用快取機制。範例是加在@SpringBootApplication類別DemoApplication

DemoApplication

package com.abc.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@EnableCaching // 啟用快取
@SpringBootApplication
public class DemoApplication {

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

}

DemoController提供對外API接收外部請求,並轉呼叫EmployeService取得資源。

DemoController

package com.abc.demo.controller;

import com.abc.demo.model.Employee;
import com.abc.demo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/employee/{id}")
    public Employee getEmployee(@PathVariable Long id) {
        return employeeService.getEmployeeById(id);
    }
    
}

Employee為被檢索的資料物件。

Employee

package com.abc.demo.model;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {

    private Long id;
    private String name;
    private Integer age;

}

EmployeeServicegetEmployeeById()方法用來查詢資料庫的員工資訊,這邊以簡單的Map物件模擬現有的員工資料。

getEmployeeById()前加上@Cacheable對此方法做快取,則當以相同的查訊條件再次呼叫getEmployeeById()時會從快取回傳先前的查詢結果。

@Cacheablevalue屬性作用同cacheNames用來指定快取名稱,也就是application.properites中設定的spring.cache.cache-names

EmployeeService

package com.abc.demo.service;

import com.abc.demo.model.Employee;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class EmployeeService {

    @Cacheable(value = "employee_cache")
    public Employee getEmployeeById(Long id) {
        Map<Long, Employee> currentEmployeeMap = getCurrentEmployeeMap();
        return currentEmployeeMap.get(id);
    }

    // 模擬資料庫的資料
    private Map<Long, Employee> getCurrentEmployeeMap() {
        Map<Long, Employee> currentEmployeeMap = new HashMap<>();
        currentEmployeeMap.put(1L, Employee.builder().id(1L).name("alan").age(33).build());
        currentEmployeeMap.put(2L, Employee.builder().id(2L).name("bill").age(45).build());
        currentEmployeeMap.put(3L, Employee.builder().id(3L).name("carl").age(24).build());
        currentEmployeeMap.put(4L, Employee.builder().id(4L).name("dave").age(31).build());
        return currentEmployeeMap;
    }

}

完成以上後啟動專案進行測試。在EmployeeService.getEmployeeById()中下中斷點,然後以debug模式啟動。

用Postman呼叫http://localhost:8080/demo/employee/1,可以發現第一次呼叫時會進入EmployeeService.getEmployeeById(),但第二次呼叫時就不會進入了,這就是快取的效果。當再次請求相同的資源時,Spring Boot Cache會以proxy的方式改從快取ConcurrentHashMap取得先前查詢過的資料。

若要手動清理快取,可使用@CacheEvict來清除快取中的資料。


完整程式碼參考github


沒有留言:

張貼留言