综合概述

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.</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.</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1..RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.louis.springboot</groupId>
<artifactId>demo</artifactId>
<version>0.0.-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.</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.</version>
</dependency>
<!-- spymemcached -->
<dependency>
<groupId>net.spy</groupId>
<artifactId>spymemcached</artifactId>
<version>2.12.</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=

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", , "louis");
// 取出缓存
Object value = memcachedClient.get("name");
System.out.println(value);
// 多线程睡眠5秒,让
Thread.sleep();
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。

相关导航

Spring Boot 系列教程目录导航

Spring Boot:快速入门教程

Spring Boot:整合Swagger文档

Spring Boot:整合MyBatis框架

Spring Boot:实现MyBatis分页

源码下载

码云:https://gitee.com/liuge1988/spring-boot-demo.git


作者:朝雨忆轻尘
出处:https://www.cnblogs.com/xifengxiaoma/
版权所有,欢迎转载,转载请注明原文作者及出处。

Spring Boot:使用Memcached缓存的更多相关文章

  1. Spring Boot 2 (八):Spring Boot 集成 Memcached

    Spring Boot 2 (八):Spring Boot 集成 Memcached 一.Memcached 介绍 Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数 ...

  2. spring boot guava cache 缓存学习

    http://blog.csdn.net/hy245120020/article/details/78065676 ****************************************** ...

  3. Spring Boot 结合 Redis 缓存

    Redis官网: 中:http://www.redis.cn/ 外:https://redis.io/ redis下载和安装 Redis官方并没有提供Redis的Windows版本,这里使用微软提供的 ...

  4. Spring Boot 入门之缓存和 NoSQL 篇(四)

    原文地址:Spring Boot 入门之缓存和 NoSQL 篇(四) 博客地址:http://www.extlight.com 一.前言 当系统的访问量增大时,相应的数据库的性能就逐渐下降.但是,大多 ...

  5. Spring Boot中使用缓存

    Spring Boot中使用缓存 随着时间的积累,应用的使用用户不断增加,数据规模也越来越大,往往数据库查询操作会成为影响用户使用体验的瓶颈,此时使用缓存往往是解决这一问题非常好的手段之一. 原始的使 ...

  6. Spring Boot中的缓存支持(一)注解配置与EhCache使用

    Spring Boot中的缓存支持(一)注解配置与EhCache使用 随着时间的积累,应用的使用用户不断增加,数据规模也越来越大,往往数据库查询操作会成为影响用户使用体验的瓶颈,此时使用缓存往往是解决 ...

  7. Spring Boot自定义Redis缓存配置,保存value格式JSON字符串

    Spring Boot自定义Redis缓存,保存格式JSON字符串 部分内容转自 https://blog.csdn.net/caojidasabi/article/details/83059642 ...

  8. Spring Boot 集成 Ehcache 缓存,三步搞定!

    作者:谭朝红 www.ramostear.com/articles/spring_boot_ehcache.html 本次内容主要介绍基于Ehcache 3.0来快速实现Spring Boot应用程序 ...

  9. (转)Spring Boot 2 (八):Spring Boot 集成 Memcached

    http://www.ityouknow.com/springboot/2018/09/01/spring-boot-memcached.html Memcached 介绍 Memcached 是一个 ...

  10. Spring Boot 2.0(八):Spring Boot 集成 Memcached

    Memcached 介绍 Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站 ...

随机推荐

  1. Scala & IntelliJ IDEA环境搭建升级版:在JAVA中调用Scala的helloworld

    --------------------- 前言 --------------------- 项目关系,希望用Spark GraphX做数据分析及图像展示,但前提是得会spark:spark是基于sc ...

  2. 【转】Mybatis传多个参数(三种解决方案)

    转自: http://www.2cto.com/database/201409/338155.html 据我目前接触到的传多个参数的方案有三种. 第一种方案: DAO层的函数方法 Public Use ...

  3. Win32 Windows计划 十一年

    一个.使用位图 1 位图 - 由图像上的各点的颜色被保存,生成对应的位图文件 栅格 - 保存图像可以理解为晶格 矢量图 - 能够理解为画图命令的保存 2 位图的使用 2.1 载入位图 LoadBitm ...

  4. Android Studio右键选项中没有Git?

    从Git clone一个Project并打开后,都会习惯性的像使用Eclipse一样,选中project右键,选择Git的相应版本号控制选项. 例如以下图,你仅仅看到了svn. 怎样配置才干在右键选项 ...

  5. youwuku和koudaitong以及weimeng差异

    优库通过涨势没有口袋,通过口袋里的东西优库有, 就像一个商场的处理这些极端类别似, 所不同的是:1.掌上通免费,但也开始掏腰包通过用户收费,因为一些特殊的.这意味着,天下没有免费的午餐,掌上通是使用完 ...

  6. 辛星与您彻底解决CSS浮子(下一个)

    上述博客文章,我们解释如何使用CSS浮子,这是一个看我们如何解释清除CSS浮子.其实CSS浮动是很清楚easy,只需要使用clear它财产,至于如何利用好它.很多人可能会表决雾,我是个新手的时候还经常 ...

  7. WPF编游戏系列 之八 银行界面及金额校验

    原文:WPF编游戏系列 之八 银行界面及金额校验        在前面<WPF编游戏系列 之四 用户控件>一文中通过用户控件创建了"My Shop"中物品列表框.本篇继 ...

  8. asp .net core 读取读取Views文件夹下的js和css

    //读取Views文件夹下的js和css app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFilePro ...

  9. MyBatis 模板

    mybatis-config.xml: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE co ...

  10. Lambda表达式的参数捕获

    以常用的Action委托为例: 有如下3个无参数的方法: public void Function() { //Do something } public void Function2() { //D ...