1 概述
Memcached 常用做集中式缓存,后续的高版本支持分布式扩展,通过内存进行数据存储,保证数据的高效读取。Memcached 通过magent 代理进行HA 高可用的访问,通过Master - Slave 的形式。保证数据的灾备。通过keepalived 来进行vip 的漂移切换,保证magent 不是单点。
通常我们为了加快程序的性能,会对热点数据进行缓存,缓存对频率更新不是特别快的数据及部分趋势端数据。常用缓存的场景如下:
1)全局序列
2)全局会话
3)热点数据缓存
4)趋势数据
5)配置数据
2 常用的客户端
一种是Xmemcached ,一种是Spymemcached ,性能可参照此博客:https://www.iteye.com/blog/dennis-zane-345887
如果要在生产上使用,最好亲自进行客户端的多方面测试(包括性能、安全、使用)
3 安全性
Memcached 不推荐在公网使用,一般在内网使用,本身并不支持安全性校验,可以通过指定访问IP 和防火墙以及不使用默认端口的情况下做一些安全防护,同时启动时以最小用户权限的方式进行。
4 pom.xml 依赖文件
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>net.spy</groupId>
<artifactId>spymemcached</artifactId>
<version>2.12.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
5 application.properties
memcache.ip=ip
memcache.port=11211
6 自定义配置加载
常用Bean 的写法,通过属性的方式进行访问。SpringBoot 中通过 @ConfigurationProperties(prefix = "memcache") 注解 ,自动加载属性文件中的值,需要注意,属性文件中的前缀需要指定,key 需要与当前定义的属性Bean 中字段保持一致。同时为了SpringBoot 初始化时加载,需要添加@Component 注解。
@Component
@ConfigurationProperties(prefix = "memcache")
public class MemcacheCfg {
private String ip;
private int port;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
7 连接初始化
可以通过SpringBoot CommandLineRunner 启动类,进行客户端连接初始化。可以通过Memcached 的客户端进行常用的操作了。
@Component
public class MemcachedRunner implements CommandLineRunner {
@Resource
private MemcacheCfg memcacheCfg;
private MemcachedClient client = null;
@Override
public void run(String... args) throws Exception {
try {
client = new MemcachedClient(new InetSocketAddress(memcacheSource.getIp(),memcacheSource.getPort()));
} catch (IOException e) {
logger.error("inint MemcachedClient failed ",e);
}
}
总结:SpringBoot 集成Memcached 很方便。操作也很简洁,现在大部分使用分布式缓存 Redis,特别向电商的秒杀场景,运维监控系统中告警处理。但是某些方面做多级缓存时,还是需要使用的。memcached 结合redis 发挥大作用,具体需要结合业务场景进行。