官网:http://memcached.org/
Memcached 安装包下载
linux版本:https://github.com/memcached/memcached/wiki/ReleaseNotes1515
查看历史版本:
选择对应历史版本下载即可:
Windows版本:
官网上并未提供 Memcached 的 Windows 平台安装包。
我们可以使用以下链接来下载,你需要根据自己的系统平台及需要的版本号点击对应的链接下载即可:
32位系统 1.2.5版本:http://static.jyshare.com/download/memcached-1.2.5-win32-bin.zip
32位系统 1.2.6版本:http://static.jyshare.com/download/memcached-1.2.6-win32-bin.zip
32位系统 1.4.4版本:http://static.jyshare.com/download/memcached-win32-1.4.4-14.zip
64位系统 1.4.4版本:http://static.jyshare.com/download/memcached-win64-1.4.4-14.zip
32位系统 1.4.5版本:http://static.jyshare.com/download/memcached-1.4.5-x86.zip
64位系统 1.4.5版本:http://static.jyshare.com/download/memcached-1.4.5-amd64.zip
安装
在 1.4.5 版本以前 memcached 可以作为一个服务安装,进入安装目录,使用**【管理员权限】**运行以下命令:
- 安装:memcached.exe -d install
- 启动:memcached.exe -d start
- 关闭:memcached.exe -d stop
安装问题:Memcached:“Failed to ignore SIGHUP: No error”
解决方式:
命令行中输入:schtasks /create /sc onstart /tn memcached /tr “‘memcached.exe’ -m 512” ,回车
注意:c:\memcached\memcached.exe替换自己的安装地址,更多安装细节请参考memcached 安装
见如下:
检查memcached是否安装成功
4、查看memcached是否安装成功,方法一:进入memcached安装目录,输入一下命令:memcached –h,出现如下截图内容,证明安装成功,能够显示版本为1.4.4
SpringBoot集成-SpyMemcached方式
application.yml配置:
memcached:
#连接池大小即客户端个数
connectionPoolSize: 1
# failureMode: true
#主机或IP地址:端口号
servers: 127.0.0.1:11211
#指定要使用的协议(BINARY,TEXT),默认是TEXT
protocol: BINARY
#以毫秒为单位设置默认的操作超时时间
opTimeout: 3000
#超时异常阈值,一般大于timeout
timeoutExceptionThreshold: 1998
# 设置定位器类型(ARRAY_MOD,CONSISTENT),默认是ARRAY_MOD
locatorType: CONSISTENT
#设置故障模式(取消,重新分配,重试),默认是重新分配
failureMode: Redistribute
#想使用Nagle算法,设置为true
useNagleAlgorithm: false
添加依赖spymemcached
<dependency>
<groupId>net.spy</groupId>
<artifactId>spymemcached</artifactId>
<version>2.12.3</version>
</dependency>
MemcachedConfig实体配置:
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.FailureMode;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.spring.MemcachedClientFactoryBean;
import net.spy.memcached.transcoders.SerializingTranscoder;
import org.ehcache.config.builders.ConfigurationBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* https://blog.csdn.net/u013725455/article/details/52102170
*/
@Configuration
public class MemcachedConfig {
@Value("${memcached.servers}")
private String servers;
@Value("${memcached.protocol}")
private ConnectionFactoryBuilder.Protocol protocol;
@Value("${memcached.opTimeout}")
private Integer timout;
@Value("${memcached.failureMode}")
private FailureMode failureMode;
@Value("${memcached.timeoutExceptionThreshold}")
private int timeoutExceptionThreshold;
@Bean
public MemcachedClient memcachedClient() throws Exception {
MemcachedClientFactoryBean bean = new MemcachedClientFactoryBean();
//以毫秒为单位设置默认的操作超时时间
bean.setOpTimeout(timout);
//主机或IP地址:端口号
bean.setServers(servers);
//设置故障模式(取消,重新分配,重试),默认是重新分配
bean.setFailureMode(failureMode);
//设置默认的转码器
bean.setTranscoder(new SerializingTranscoder(1024));
ConnectionFactoryBuilder cb = new ConnectionFactoryBuilder();
//指定要使用的协议(BINARY,TEXT),默认是TEXT
bean.setProtocol(protocol);
// 想使用Nagle算法,设置为true
bean.setUseNagleAlgorithm(true);
// 超时异常阈值,一般大于timeout
bean.setTimeoutExceptionThreshold(timeoutExceptionThreshold);
// 设置定位器类型(ARRAY_MOD,CONSISTENT),默认是ARRAY_MOD
bean.setLocatorType(ConnectionFactoryBuilder.Locator.CONSISTENT);
bean.afterPropertiesSet();//实例化客户端MemcachedClient
MemcachedClient memcachedClient =(MemcachedClient)bean.getObject();
return memcachedClient;
}
}
memcache工具类
/*
* 文件名:spymemcached.java
* 描述: spymemcached.java
*/
import net.spy.memcached.MemcachedClient;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketAddress;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import net.spy.memcached.ConnectionObserver;
import net.spy.memcached.transcoders.Transcoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
/**
* memcache工具
* <p>
* TODO 详细描述
* <p>
* TODO 示例代码 <pre>
* </pre>
*
*/
@Configuration
public class MemcachedUtils {
/**
* memcached实例.
*/
@Autowired
private MemcachedClient memcachedClient;
private final int DEFAULT_TIMEOUT=3000;
/**
*
* TODO 添加方法注释.
*
* @param obs obs
*/
public void addObserver(ConnectionObserver obs) {
memcachedClient.addObserver(obs);
}
/**
*
* TODO 添加方法注释.
*
* @param obs obs
*/
public void removeObserver(ConnectionObserver obs) {
memcachedClient.removeObserver(obs);
}
/**
*
* 加入缓存.
*
* @param key key
* @param value value
* @param expire 过期时间
* @return boolean
*/
public boolean set(String key, Object value, int expire) {
Future<Boolean> f = memcachedClient.set(key, expire, value);
return getBooleanValue(f);
}
/**
*
*从缓存中获取.
*
* @param key key
* @return Object
*/
public Object get(String key) {
return memcachedClient.get(key);
}
/**
*从缓存中获取.
* @param key key
* @return Object
*/
public Object asyncGet(String key) {
Object obj = null;
Future<Object> f = memcachedClient.asyncGet(key);
try {
obj = f.get(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
} catch (Exception e) {
f.cancel(false);
}
return obj;
}
/**
*
* 加入缓存.
*
* @param key key
* @param value value
* @param expire 过期时间
* @return boolean
*/
public boolean add(String key, Object value, int expire) {
Future<Boolean> f = memcachedClient.add(key, expire, value);
return getBooleanValue(f);
}
/**
*
* 替换.
*
* @param key key
* @param value value
* @param expire 过期时间
* @return boolean
*/
public boolean replace(String key, Object value, int expire) {
Future<Boolean> f = memcachedClient.replace(key, expire, value);
return getBooleanValue(f);
}
/**
*
* 从缓存中删除.
*
* @param key key
* @return boolean
*/
public boolean delete(String key) {
Future<Boolean> f = memcachedClient.delete(key);
return getBooleanValue(f);
}
/***
*
* flush.
*
* @return boolean
*/
public boolean flush() {
Future<Boolean> f = memcachedClient.flush();
return getBooleanValue(f);
}
/**
* 从缓存中获取.
* @param keys keys
* @return Map<String, Object>
*/
public Map<String, Object> getMulti(Collection<String> keys) {
return memcachedClient.getBulk(keys);
}
/**
*
* 从缓存中获取.
*
* @param keys keys
* @return Map<String, Object>
*/
public Map<String, Object> getMulti(String[] keys) {
return memcachedClient.getBulk(keys);
}
/**
*
* 从缓存中获取.
*
* @param keys keys
* @return Map<String, Object>
*/
public Map<String, Object> asyncGetMulti(Collection<String> keys) {
Map<String, Object> map = null;
Future<Map<String, Object>> f = memcachedClient.asyncGetBulk(keys);
try {
map = f.get(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
} catch (Exception e) {
f.cancel(false);
}
return map;
}
/**
*
* 从缓存中获取.
*
* @param keys keys
* @return Map<String, Object>
*/
public Map<String, Object> asyncGetMulti(String[] keys) {
Map<String, Object> map = null;
Future<Map<String, Object>> f = memcachedClient.asyncGetBulk(keys);
try {
map = f.get(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
} catch (Exception e) {
f.cancel(false);
}
return map;
}
// ---- Basic Operation End ----//
// ---- increment & decrement Start ----//
public long increment(String key, int by, long defaultValue, int expire) {
return memcachedClient.incr(key, by, defaultValue, expire);
}
public long increment(String key, int by) {
return memcachedClient.incr(key, by);
}
public long decrement(String key, int by, long defaultValue, int expire) {
return memcachedClient.decr(key, by, defaultValue, expire);
}
public long decrement(String key, int by) {
return memcachedClient.decr(key, by);
}
public long asyncIncrement(String key, int by) {
Future<Long> f = memcachedClient.asyncIncr(key, by);
return getLongValue(f);
}
public long asyncDecrement(String key, int by) {
Future<Long> f = memcachedClient.asyncDecr(key, by);
return getLongValue(f);
}
// ---- increment & decrement End ----//
public void printStats() throws IOException {
printStats(null);
}
public void printStats(OutputStream stream) throws IOException {
Map<SocketAddress, Map<String, String>> statMap = memcachedClient.getStats();
if (stream == null) {
stream = System.out;
}
StringBuffer buf = new StringBuffer();
Set<SocketAddress> addrSet = statMap.keySet();
Iterator<SocketAddress> iter = addrSet.iterator();
while (iter.hasNext()) {
SocketAddress addr = iter.next();
buf.append(addr.toString() + "/n");
Map<String, String> stat = statMap.get(addr);
Set<String> keys = stat.keySet();
Iterator<String> keyIter = keys.iterator();
while (keyIter.hasNext()) {
String key = keyIter.next();
String value = stat.get(key);
buf.append(" key=" + key + ";value=" + value + "/n");
}
buf.append("/n");
}
stream.write(buf.toString().getBytes());
stream.flush();
}
public Transcoder getTranscoder() {
return memcachedClient.getTranscoder();
}
private long getLongValue(Future<Long> f) {
try {
Long l = f.get(DEFAULT_TIMEOUT,TimeUnit.SECONDS);
return l.longValue();
} catch (Exception e) {
f.cancel(false);
}
return -1;
}
private boolean getBooleanValue(Future<Boolean> f) {
try {
Boolean bool = f.get(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
return bool.booleanValue();
} catch (Exception e) {
f.cancel(false);
return false;
}
}
}
2 XMemcached方式:
pom 依赖
<dependency>
<groupId>com.googlecode.xmemcached</groupId>
<artifactId>xmemcached</artifactId>
<version>2.0.0</version>
</dependency>
配置类XMemcachedConfig:
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.TextCommandFactory;
import net.rubyeye.xmemcached.impl.ArrayMemcachedSessionLocator;
import net.rubyeye.xmemcached.transcoders.SerializingTranscoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* https://blog.csdn.net/u013725455/article/details/52102170
*/
@Configuration
public class XMemcachedConfig {
@Value("${memcached.servers}")
private String servers;
@Value("${memcached.opTimeout}")
private Integer timeout;
@Value("${memcached.timeoutExceptionThreshold}")
private int timeoutExceptionThreshold;
@Bean
public MemcachedClient xmemcachedClient() throws Exception {
//主机或IP地址:端口号
XMemcachedClientBuilder builder = new XMemcachedClientBuilder(servers);
//以毫秒为单位设置默认的操作超时时间
builder.setOpTimeout(timeout);
builder.setSessionLocator(new ArrayMemcachedSessionLocator());
builder.setFailureMode(false);
builder.setConnectionPoolSize(10);
builder.setCommandFactory(new TextCommandFactory());
//设置默认的转码器
builder.setTranscoder(new SerializingTranscoder(1024));
MemcachedClient memcachedClient =builder.build();
return memcachedClient;
}
}
工具类
import net.rubyeye.xmemcached.MemcachedClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
@Configuration
public class XMemcachedUtils {
@Autowired
private MemcachedClient xmemcachedClient;
private int DEFAULT_EXPIRE=36000;
public boolean set(String key, Object value) {
try {
return xmemcachedClient.set(key,DEFAULT_EXPIRE,value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Object get(String key) {
try {
return xmemcachedClient.get(key);
} catch (Exception e) {
throw new RuntimeException(e);
}
} public Object delete(String key) {
try {
return xmemcachedClient.delete(key);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Memcached Client目前有3种:
Memcached Client for Java
SpyMemcached
XMemcached
这三种Client一直存在各种争议:
- Memcached Client for Java 比 SpyMemcached更稳定、更早、更广泛;
- SpyMemcached 比 Memcached Client for Java更高效;
- XMemcached 比 SpyMemcache并发效果更好。
常用的工具:
redis/memcache监控管理工具——treeNMS
- Memcached命令行工具
Memcached自带了一些基本的命令行工具,用于与Memcached服务器交互。最常用的是telnet或nc(Netcat),它们允许你直接发送Memcached命令。例如:
查看统计信息:
telnet localhost 11211
stats
- MCStats
MCStats是一个用于显示Memcached服务器统计信息的命令行工具。它可以以更友好的格式展示stats命令的结果,便于快速分析Memcached的状态。
MemAdmin是一个基于Web的Memcached管理工具。它提供了一个图形界面,用于监控和管理Memcached服务器,包括查看统计数据、管理缓存项、以及执行各种Memcached命令。
- TreeNMS
一款采用JAVA开发的Redis和Memcache可视化客户端工具,实现基于WEB方式对Redis和Memcached数据库进行管理、维护。它提供了NoSQL数据库的展示、库表的展示、key, value的展示、新增、修改、删除等数据的在线编辑维护、数据库备份还原等功能。TreeNMS系统内置了14套UI皮肤,使用中可以依个人喜好选择配色方案 - mcdump
mcdump是一个命令行工具,用于从Memcached服务器转储缓存的内容。它可以帮助你查看当前缓存中存储了哪些键值对,这对于调试和分析缓存策略非常有用。
- mcslap
mcslap是Memcached自带的一个压力测试工具,用于评估Memcached服务器的性能。它可以通过并发发送大量的请求来模拟真实世界的负载,帮助你了解Memcached在高负载下的表现。
- Memcached Tools Collection
这是一个由多个小工具组成的集合,包括mctop(类似于top命令,用于实时监控Memcached服务器的性能)、mcflush(用于清空Memcached缓存)等。
- 第三方监控工具
除了上述专门针对Memcached的工具,还有许多通用的监控和可视化工具可以用来监控Memcached的性能,如Grafana、Prometheus、Nagios、Zabbix等。这些工具通常需要配合相应的插件或导出器来收集Memcached的指标。
参考:
https://blog.csdn.net/u013725455/article/details/52102170
https://blog.csdn.net/weixin_41850878/article/details/140434106