綜合概述
Memcached是一個自由開源的,高性能,分布式內存對象緩存系統。Memcached基於內存的key-value存儲,用來存儲小塊的任意數據,這些數據可以是數據庫調用、API調用或者是頁面渲染的結果。通過Memcached緩存數據庫查詢結果,可以有效地減少數據庫訪問次數,進而提高動態Web應用的速度。雖然Memcached的守護進程是用C寫的,但是客戶端可以用任何語言來編寫,並通過Memcached協議與守護進程進行通信。
因為Spring Boot暫時還沒有提供 Memcached相關的支持包,因此需要我們通過集成第三方提供的Memcached客戶端來實現。Spymemcached是官方推出的一個Memcached Java客戶端,使用NIO實現,異步、單線程,在性能上表現出色,廣泛應用於Java + Memcached項目中。
實現案例
接下來,我們就用一個簡單的案例來說明在Spring Boot中如何使用Memcached緩存技術。
首先,需要安裝Memcached,教程很多,這里不再贅述。可以參考:Memcached安裝教程。
生成項目模板
為方便我們初始化項目,Spring Boot給我們提供一個項目模板生成網站。
1. 打開瀏覽器,訪問:https://start.spring.io/
2. 根據頁面提示,選擇構建工具,開發語言,項目信息等。
3. 點擊 Generate the project,生成項目模板,生成之后會將壓縮包下載到本地。
4. 使用IDE導入項目,我這里使用Eclipse,通過導入Maven項目的方式導入。
添加相關依賴
清理掉不需要的測試類及測試依賴,添加 Maven 相關依賴,這里需要添加上web、swagger和spymemcached的依賴,Swagger是為了方便接口測試。
對於spymemcached的支持,其實只要如下這個依賴包就可以了。
<!-- spymemcached --> <dependency> <groupId>net.spy</groupId> <artifactId>spymemcached</artifactId> <version>2.12.3</version> </dependency>
完整的POM文件內容如下。
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 http://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.1.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.louis.springboot</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <!-- spymemcached --> <dependency> <groupId>net.spy</groupId> <artifactId>spymemcached</artifactId> <version>2.12.3</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
添加相關配置
1.添加swagger 配置
添加一個swagger 配置類,在工程下新建 config 包並添加一個 SwaggerConfig 配置類,除了常規配置外,加了一個令牌屬性,可以在接口調用的時候傳遞令牌。
SwaggerConfig.java
package com.louis.springboot.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()).build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("Swagger API Doc") .description("This is a restful api document of Swagger.") .version("1.0") .build(); } }
2.在配置文件添加memcache的主機端口信息
application.properties
memcache.ip=127.0.0.1 memcache.port=11211
3.添加一個MemcacheConfig配置類,讀取主機端口並構造一個MemcachedClient。
MemcacheConfig.java
package com.louis.springboot.demo.config; import java.io.IOException; import java.net.InetSocketAddress; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import net.spy.memcached.MemcachedClient; @Configuration public class MemcacheConfig { @Value("${memcache.ip}") private String ip; @Value("${memcache.port}") private int port; @Bean public MemcachedClient getClient() { MemcachedClient memcachedClient = null; try { memcachedClient = new MemcachedClient(new InetSocketAddress(ip, port)); } catch (IOException e) { e.printStackTrace(); } return memcachedClient; } }
編寫業務接口
編寫一個業務控制器,通過MemcachedClient實現對緩存的設置和讀取。
MemcacheController.java
package com.louis.springboot.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import net.spy.memcached.MemcachedClient; import net.spy.memcached.internal.OperationFuture; @RestController public class MemcacheController { @Autowired private MemcachedClient memcachedClient; @GetMapping("/memcache") public String memcache() throws InterruptedException { // 放入緩存, 如下參數key為name,值為louis,過期時間為5000,單位為毫秒 OperationFuture<Boolean> flag = memcachedClient.set("name", 5000, "louis"); // 取出緩存 Object value = memcachedClient.get("name"); System.out.println(value); // 多線程睡眠5秒,讓 Thread.sleep(5000); value = memcachedClient.get("name"); System.out.println(value); return "success"; } }
編譯運行測試
1. 右鍵項目 -> Run as -> Maven install,開始執行Maven構建,第一次會下載Maven依賴,可能需要點時間,如果出現如下信息,就說明項目編譯打包成功了。
2. 右鍵文件 DemoApplication.java -> Run as -> Java Application,開始啟動應用,當出現如下信息的時候,就說明應用啟動成功了,默認啟動端口是8080。
3. 打開瀏覽器,訪問:http://localhost:8080/swagger-ui.html,進入swagger接口文檔界面。
4.調用memcache接口,測試緩存存取操作,查看控制台輸出結果。
louis null
寫入數據時設置name=louis,過期時間為5秒,第一次獲取name結果為louis,在睡眠5秒之后第二次獲取name時,因為過期返回null。
相關導航
源碼下載
碼雲:https://gitee.com/liuge1988/spring-boot-demo.git
作者:朝雨憶輕塵
出處:https://www.cnblogs.com/xifengxiaoma/
版權所有,歡迎轉載,轉載請注明原文作者及出處。