专属目录
Spring Boot 集成 Memcached
引言
今天有一个高性能的分布式内存对象缓存系统
,想给大家分享一下,用于动态Web应用
以减轻数据库负载
,它就是 —— Memcached
。 其实现在来说 Memcached
的话估计会有点过气
,因为现在大势基本都在 Redis
。但是还是会有很多公司的项目是很早前开发的,使用的技术自然也就是比较早点的技术,缓存技术使用的也是 Memcached
,这些项目也自然需要去维护,更新,如果你还不会的话,就快来物色物色!
首先,我先带大家了解下 Memcached!
Memcached 介绍
Memcached
是一个 高性能的分布式内存对象缓存系统
,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态、数据库驱动网站的速度
。
Memcached
是以 LiveJournal
旗下 Danga Interactive 公司
的 Brad Fitzpatric
为首开发的一款软件
Memcached
是一种基于内存的键值(key-value)存储,用来存储小块的任意数据(字符串、对象)。这些数据可以是数据库调用、API调用或者是页面渲染的结果。其存储性能在某些方面不比 redis差,甚至在文本类型数据
的存储上性能略优于 redis
,
一般的使用目的是,通过缓存数据库查询结果,减少数据库访问次数,以提高动态Web应用的速度、提高可扩展性
。
特性
Memcached
作为高速运行的分布式缓存服务器
,具有以下的特点
-
协议简单
-
基于 libevent 的事件处理
-
内置内存存储方式
-
memcached 不互相通信的分布式
因我们今天要说 Spring Boot
集成 Memcached
,而 Spring Boot
并没有
针对 Memcached
提供对应的组建包,因此需要我们自己来集成
。
在集成前我们首先需要选择一款客户端
来连接对象,类似于我们在使用 Redis
时使用的 Jedis
, 而目前 memcached
主流的客户端
是 Xmemcached
XMemcached 介绍
XMemcached
是 Java
中的高性能
,易于使用
的阻塞多线程 memcached 客户端
。
它是基于 nio
的,并经过精心调校以获得最佳性能
。因高性能,稳定可靠,现已经在众多公司的众多项目里得到应用。
该介绍的也说完了,接下来我们说下该如何集成使用呢!
集成过程
一、 依赖配置
添加依赖
在对应的项目 pom.xml
中引入 XMemcached
的依赖包
<!-- 引入 XMemcached 客户端依赖包 -->
<!-- https://mvnrepository.com/artifact/com.googlecode.xmemcached/xmemcached -->
<dependency>
<groupId>com.googlecode.xmemcached</groupId>
<artifactId>xmemcached</artifactId>
<version>2.4.5</version>
</dependency>
<!-- 使用注解处理器来生成自己的元数据 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
添加配置
在 Spring Boot
中的配置 memcached
, yml
与 properties
选一种配置即可
application.yml
# memcached配置
memcached:
#memcached服务器节点(格式为host:port) IP:端口号
servers: 127.0.0.1:11211
# 设置接口操作的默认超时时间,可以被接口覆盖
opTimeout: 3000
# nio连接池的数量
poolSize: 10
# 是否启用失败模式,默认为false
failureMode: false
# 是否使用memcached缓存
enabled: true
application.properties
memcache.servers=127.0.0.1:11211
memcache.opTimeout=3000
memcache.poolSize=10
memcache.failureMode=false
memcache.enabled=true
IP与端口等记得改为自己的。
二、 创建 MemcachedProperties 类,接收及调用配置信息
MemcachedProperties
类
package com.example.springbootmemcachexmemcached.memcache.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* @ClassName: XMemcachedProperties
* @Description: (描述) XMemcached 配置属性,读取的是 yml / properties 文件中 memcached 开头的属性
* @Author: WHT
* @Version: V1.0
* @Date: 2020/10/12 11:38
*/
@Data
@PropertySource("classpath:application.yml")
@ConfigurationProperties(prefix = "memcached")
@Component
public class XMemcachedProperties {
/**
* memcached服务器节点
*/
private String servers;
/**
* 设置默认操作超时
*/
private Long opTimeout;
/**
* nio连接池的数量
*/
private Integer poolSize;
/**
* 是否开启失败模式
*/
private Boolean failureMode;
/**
* 是否使用memcached缓存
*/
private Boolean enabled;
}
@ConfigurationProperties(prefix = "memcached")
的意思会以 memcached
为开头的属性加载到对应的配置文件中。
三、 创建 MemcachedConfig 初始化配置类,启动初始化 MemcachedClient
创建memcached客户端
对象,并注入spring容器
中
package com.example.springbootmemcachexmemcached.memcache.config;
import com.example.springbootmemcachexmemcached.properties.XMemcachedProperties;
import lombok.extern.slf4j.Slf4j;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @ClassName: MemcachedConfig
* @Description: (描述)
* @Author: WHT
* @Version: V1.0
* @Date: 2020/10/12 15:52
*/
@Configuration
@Slf4j
public class MemcachedConfig {
@Autowired
private XMemcachedProperties xMemcachedProperties;
@Bean(name = "memcachedClientBuilder")
public MemcachedClientBuilder getBuilder() {
MemcachedClientBuilder memcachedClientBuilder = new XMemcachedClientBuilder(xMemcachedProperties.getServers());
// 内部采用一致性哈希算法
memcachedClientBuilder.setSessionLocator(new KetamaMemcachedSessionLocator());
// 操作的超时时间
memcachedClientBuilder.setOpTimeout(xMemcachedProperties.getOpTimeout());
// 采用二进制传输协议(默认为文本协议)
memcachedClientBuilder.setCommandFactory(new BinaryCommandFactory());
// 设置连接池的大小
memcachedClientBuilder.setConnectionPoolSize(xMemcachedProperties.getPoolSize());
// 是否开起失败模式
memcachedClientBuilder.setFailureMode(xMemcachedProperties.getFailureMode());
return memcachedClientBuilder;
}
/**
* 由Builder创建memcachedClient对象,并注入spring容器中
*
* @param memcachedClientBuilder
* @return MemcachedClient
*/
@Bean(name = "memcachedClient")
public MemcachedClient getClient(@Qualifier("memcachedClientBuilder") MemcachedClientBuilder memcachedClientBuilder) {
MemcachedClient client = null;
try {
client = memcachedClientBuilder.build();
} catch (Exception e) {
log.info("exception happens when bulid memcached client{}", e.toString());
}
return client;
}
}
四、 测试使用
直接使用 SpringBootTest
进行测试
给 Test 基础类添加 开始和结束测试
SpringBootMemcacheXmemcachedApplicationTests 基础类
package com.example.springbootmemcachexmemcached;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @ClassName: SpringBootMemcacheXmemcachedApplicationTests
* @Description: (描述) SpringBootTest 测试基础类,其他类继承此类
* @Author: WHT
* @Version: V1.0
* @Date: 2020/10/12 15:55
*/
@RunWith(SpringRunner.class)
@Slf4j
@SpringBootTest
class SpringBootMemcacheXmemcachedApplicationTests {
private Long time;
@Test
void contextLoads() {
}
@Before
public void setUp() {
this.time = System.currentTimeMillis();
log.info("==> 测试开始执行 <==");
}
@After
public void tearDown() {
log.info("==> 测试执行完成,耗时:{} ms <==", System.currentTimeMillis() - this.time);
}
}
Memcached 测试类
继承 SpringBootTest测试基础类
MemcachedTest 测试类
package com.example.springbootmemcachexmemcached;
import lombok.extern.slf4j.Slf4j;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeoutException;
/**
* @ClassName: MemcachedTest
* @Description: (描述) Memcached 测试
* @Author: WHT
* @Version: V1.0
* @Date: 2020/10/12 16:15
*/
@Slf4j
@Component
public class MemcachedTest extends SpringBootMemcacheXmemcachedApplicationTests {
@Autowired
private MemcachedClient memcachedClient;
@Test
public void test() throws InterruptedException, TimeoutException, MemcachedException {
// 写入缓存 dataOne ,设置缓存时间永不过期
boolean flag = memcachedClient.set("dataOne", 0, 1);
// 取出缓存
Object dataOne = memcachedClient.get("dataOne");
log.warn("dataOne is [{}]", dataOne);
int[] arr = {1, 2, 3, 4, 5};
// 写入缓存 数组 arr ,并设置 3s后过期
memcachedClient.set("arr", 3, arr);
Object arrayOne = memcachedClient.get("arr");
log.warn("arrayOne is [{}]", arrayOne);
Thread.sleep(3000);
Object arrayTwo = memcachedClient.get("arr");
log.warn("arrayTwo is [{}]", arrayTwo);
}
}
五、 运行结果
查看测试结果日志,可发现输出图中内容证明测试成功
了
示例代码
如需有小伙伴想要 示例代码
可 点击/复制
以下链接查看
总结
看到这今天的 Spring Boot 集成 Memcached 就到此完结了,是不是非常简单,非常nice,这下再也不怕数据库的压力大了。快去赶快试试!别着急,还有更多的秘密等着你来探索!
分享嗨起来,美德传起来,点个星标从此探索之路不迷茫!
微信扫描二维码,关注我的原创日更公众号,可以查看更多程序的秘密!