windows怎么应用memecached

windows怎么应用memecached,第1张

Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提供动态、数据库驱动网站的速度。Memcached基于一个存储键/值对的hashmap。其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信。但是它并不提供冗余(例如,复制其hashmap条目);当某个服务器S停止运行或崩溃了,所有存放在S上的键/值对都将丢失。
下载Windows的Server端
安装Memcache Server(也可以不安装直接启动)
1 下载memcached的windows稳定版,解压放某个盘下面,比如在c:\memcached
2 在CMD下输入 "c:\memcached\memcachedexe -d install" 安装
3 再输入:"c:\memcached\memcachedexe -d start" 启动。NOTE: 以后memcached将作为windows的一个服务每次开机时自动启动。这样服务器端已经安装完毕了。
如果下载的是二进制的版本,直接运行就可以了,可以加上参数来加以设置。
常用设置:
-p <num> 监听的端口
-l <ip_addr> 连接的IP地址, 默认是本机
-d start 启动memcached服务
-d restart 重起memcached服务
-d stop|shutdown 关闭正在运行的memcached服务
-d install 安装memcached服务
-d uninstall 卸载memcached服务
-u <username> 以<username>的身份运行 (仅在以root运行的时候有效)
-m <num> 最大内存使用,单位MB。默认64MB
-M 内存耗尽时返回错误,而不是删除项
-c <num> 最大同时连接数,默认是1024
-f <factor> 块大小增长因子,默认是125
-n <bytes> 最小分配空间,key+value+flags默认是48
-h 显示帮助

因为145开始就不是作为一个服务了,而是作为一个任务,要启动就:
1、先创建任务,在cmd内打如下指令
schtasks /create /sc onstart /tn memcached /tr "'c:\memcached\memcachedexe' -m 512"
注意:你需要使用真实的路径替代 c:\memcached\memcachedexe。
注意:-m 512 意思是设置 memcached 最大的缓存配置为512M。
注意:我们可以通过使用 "c:\memcached\memcachedexe -h" 命令查看更多的参数配置。
2、同样cmd打指令:
memcached //会没有任何反应,就表示你现在已经开启任务了
或者
手动双击你的memcachedexe ,然后就跳出个框,就启动了

PHP的Memcached的驱动会自动进行serialize和unserialize,你所需要做的是:
1 选取一个合适key,比如 "POST_OF_USER_" $userId
2 调用set函数把数据丢进去就行了
示例代码:
全选复制放进笔记// 0 准备:
$cache = new Memcache();
$cache->connect('127001', 11211); // 请替换为你的memcache服务器地址和端口
$userId = // 你自己想办法获取
// 1 构造cache KEY
$cacheKey = "POSTS_OF_USER_" $userId;
// 2 从缓存中获取数据
$posts = $cache->get($cacheKey);
if ($posts === false){
// 3 缓存失效了,加载数据
$posts = // 你自己想办法加载数据
// 4 保存数据到缓存中
$cache->set($cacheKey, $posts);
}
// OK,可以使用posts了

 本文将对在Java环境下Memcached应用进行详细介绍。Memcached主要是集群环境下的缓存解决方案,可以运行在Java或者NET平台上,这里我们主要讲的是Windows下的Memcached应用。
这些天在设计SNA的架构,接触了一些远程缓存、集群、session复制等的东西,以前做企业应用的时候感觉作用不大,现在设计面对internet的系统架构时就非常有用了,而且在调试后看到压力测试的情况还是比较好的。
在缓存的选择上有过很多的思考,虽然说memcached结合java在序列化上性能不怎么样,不过也没有更好的集群环境下的缓存解决方案了,就选择了memcached。本来计划等公司买的服务器到位装个linux再来研究memcached,但这两天在找到了一个windows下的Memcached版本,就动手开始调整现有的框架了。
Windows下的Server端很简单,不用安装,双击运行后默认服务端口是11211,没有试着去更改端口,因为反正以后会用Unix版本,到时再记录安装步骤。下载客户端的JavaAPI包,接口非常简单,参考API手册上就有现成的例子。
目标,对旧框架缓存部分进行改造:
1、缓存工具类
2、hibernate的provider
3、用缓存实现session机制
今天先研究研究缓存工具类的改造,在旧框架中部分函数用了ehcache对执行结果进行了缓存处理,现在目标是提供一个缓存工具类,在配置文件中配置使用哪种缓存(memcached或ehcached),使其它程序对具体的缓存不依赖,同时使用AOP方式来对方法执行结果进行缓存。
首先是工具类的实现:
在Spring中配置
Java代码

<bean id="cacheManager"
class="orgspringframeworkcacheehcacheEhCacheManagerFactoryBean">
<property name="configLocation">
<value>classpath:ehcachexmlvalue>
property>
bean>

<bean id="localCache"
class="orgspringframeworkcacheehcacheEhCacheFactoryBean">
<property name="cacheManager" ref="cacheManager" />
<property name="cacheName"
value="×××cacheLOCAL_CACHE" />
bean>

<bean id="cacheService"
class="×××corecacheCacheService" init-method="init" destroy-method="destory">
<property name="cacheServerList" value="${cacheservers}"/>
<property name="cacheServerWeights" value="${cachecacheServerWeights}"/>
<property name="cacheCluster" value="${cachecluster}"/>
<property name="localCache" ref="localCache"/>
bean>

<bean id="cacheManager"
class="orgspringframeworkcacheehcacheEhCacheManagerFactoryBean">
<property name="configLocation">
<value>classpath:ehcachexmlvalue>
property>
bean>
<bean id="localCache"
class="orgspringframeworkcacheehcacheEhCacheFactoryBean">
<property name="cacheManager" ref="cacheManager" />
<property name="cacheName"
value="×××cacheLOCAL_CACHE" />
bean>

<bean id="cacheService"
class="×××corecacheCacheService" init-method="init" destroy-method="destory">
<property name="cacheServerList" value="${cacheservers}"/>
<property name="cacheServerWeights" value="${cachecacheServerWeights}"/>
<property name="cacheCluster" value="${cachecluster}"/>
<property name="localCache" ref="localCache"/>
bean>
在properties文件中配置${cacheservers} ${cachecacheServerWeights} ${cachecluster}
具体工具类的代码
Java代码
/
@author Marc

/
public class CacheService {
private Log logger = LogFactorygetLog(getClass());
private Cache localCache;
String cacheServerList;
String cacheServerWeights;
boolean cacheCluster = false;
int initialConnections = 10;
int minSpareConnections = 5;
int maxSpareConnections = 50;
long maxIdleTime = 1000 60 30; // 30 minutes
long maxBusyTime = 1000 60 5; // 5 minutes
long maintThreadSleep = 1000 5; // 5 seconds
int socketTimeOut = 1000 3; // 3 seconds to block on reads
int socketConnectTO = 1000 3; // 3 seconds to block on initial
// connections If 0, then will use blocking
// connect (default)
boolean failover = false; // turn off auto-failover in event of server
// down
boolean nagleAlg = false; // turn off Nagle's algorithm on all sockets in
// pool
MemCachedClient mc;
public CacheService(){
mc = new MemCachedClient();
mcsetCompressEnable(false);
}
/
放入

/
public void put(String key, Object obj) {
AsserthasText(key);
AssertnotNull(obj);
AssertnotNull(localCache);
if (thiscacheCluster) {
mcset(key, obj);
} else {
Element element = new Element(key, (Serializable) obj);
localCacheput(element);
}
}
/
删除
/
public void remove(String key){
AsserthasText(key);
AssertnotNull(localCache);
if (thiscacheCluster) {
mcdelete(key);
}else{
localCacheremove(key);
}
}
/
得到
/
public Object get(String key) {
AsserthasText(key);
AssertnotNull(localCache);
Object rt = null;
if (thiscacheCluster) {
rt = mcget(key);
} else {
Element element = null;
try {
element = localCacheget(key);
} catch (CacheException cacheException) {
throw new DataRetrievalFailureException("Cache failure: "
+ cacheExceptiongetMessage());
}
if(element != null)
rt = elementgetValue();
}
return rt;
}
/
判断是否存在

/
public boolean exist(String key){
AsserthasText(key);
AssertnotNull(localCache);
if (thiscacheCluster) {
return mckeyExists(key);
}else{
return thislocalCacheisKeyInCache(key);
}
}
private void init() {
if (thiscacheCluster) {
String[] serverlist = cacheServerListsplit(",");
Integer[] weights = thissplit(cacheServerWeights);
// initialize the pool for memcache servers
SockIOPool pool = SockIOPoolgetInstance();
poolsetServers(serverlist);
poolsetWeights(weights);
poolsetInitConn(initialConnections);
poolsetMinConn(minSpareConnections);
poolsetMaxConn(maxSpareConnections);
poolsetMaxIdle(maxIdleTime);
poolsetMaxBusyTime(maxBusyTime);
poolsetMaintSleep(maintThreadSleep);
poolsetSocketTO(socketTimeOut);
poolsetSocketConnectTO(socketConnectTO);
poolsetNagle(nagleAlg);
poolsetHashingAlg(SockIOPoolNEW_COMPAT_HASH);
poolinitialize();
loggerinfo("初始化memcached pool!");
}
}

private void destory() {
if (thiscacheCluster) {
SockIOPoolgetInstance()shutDown();
}
}
}
/
@author Marc

/
public class CacheService {
private Log logger = LogFactorygetLog(getClass());
private Cache localCache;
String cacheServerList;
String cacheServerWeights;
boolean cacheCluster = false;
int initialConnections = 10;
int minSpareConnections = 5;
int maxSpareConnections = 50;
long maxIdleTime = 1000 60 30; // 30 minutes
long maxBusyTime = 1000 60 5; // 5 minutes
long maintThreadSleep = 1000 5; // 5 seconds
int socketTimeOut = 1000 3; // 3 seconds to block on reads
int socketConnectTO = 1000 3; // 3 seconds to block on initial
// connections If 0, then will use blocking
// connect (default)
boolean failover = false; // turn off auto-failover in event of server
// down
boolean nagleAlg = false; // turn off Nagle's algorithm on all sockets in
// pool
MemCachedClient mc;
public CacheService(){
mc = new MemCachedClient();
mcsetCompressEnable(false);
}
/
放入

/
public void put(String key, Object obj) {
AsserthasText(key);
AssertnotNull(obj);
AssertnotNull(localCache);
if (thiscacheCluster) {
mcset(key, obj);
} else {
Element element = new Element(key, (Serializable) obj);
localCacheput(element);
}
}
/
删除
/
public void remove(String key){
AsserthasText(key);
AssertnotNull(localCache);
if (thiscacheCluster) {
mcdelete(key);
}else{
localCacheremove(key);
}
}
/
得到
/
public Object get(String key) {
AsserthasText(key);
AssertnotNull(localCache);
Object rt = null;
if (thiscacheCluster) {
rt = mcget(key);
} else {
Element element = null;
try {
element = localCacheget(key);
} catch (CacheException cacheException) {
throw new DataRetrievalFailureException("Cache failure: "
+ cacheExceptiongetMessage());
}
if(element != null)
rt = elementgetValue();
}
return rt;
}
/
判断是否存在

/
public boolean exist(String key){
AsserthasText(key);
AssertnotNull(localCache);
if (thiscacheCluster) {
return mckeyExists(key);
}else{
return thislocalCacheisKeyInCache(key);
}
}
private void init() {
if (thiscacheCluster) {
String[] serverlist = cacheServerListsplit(",");
Integer[] weights = thissplit(cacheServerWeights);
// initialize the pool for memcache servers
SockIOPool pool = SockIOPoolgetInstance();
poolsetServers(serverlist);
poolsetWeights(weights);
poolsetInitConn(initialConnections);
poolsetMinConn(minSpareConnections);
poolsetMaxConn(maxSpareConnections);
poolsetMaxIdle(maxIdleTime);
poolsetMaxBusyTime(maxBusyTime);
poolsetMaintSleep(maintThreadSleep);
poolsetSocketTO(socketTimeOut);
poolsetSocketConnectTO(socketConnectTO);
poolsetNagle(nagleAlg);
poolsetHashingAlg(SockIOPoolNEW_COMPAT_HASH);
poolinitialize();
loggerinfo("初始化memcachedpool!");
}
}
private void destory() {
if (thiscacheCluster) {
SockIOPoolgetInstance()shutDown();
}
}
}
然后实现函数的AOP拦截类,用来在函数执行前返回缓存内容
Java代码
public class CachingInterceptor implements MethodInterceptor {

private CacheService cacheService;
private String cacheKey;

public void setCacheKey(String cacheKey) {
thiscacheKey = cacheKey;
}

public void setCacheService(CacheService cacheService) {
thiscacheService = cacheService;
}

public Object invoke(MethodInvocation invocation) throws Throwable {
Object result = cacheServiceget(cacheKey);
//如果函数返回结果不在Cache中,执行函数并将结果放入Cache
if (result == null) {
result = invocationproceed();
cacheServiceput(cacheKey,result);
}
return result;
}
}
public class CachingInterceptor implements MethodInterceptor {

private CacheService cacheService;
private String cacheKey;

public void setCacheKey(String cacheKey) {
thiscacheKey = cacheKey;
}

public void setCacheService(CacheService cacheService) {
thiscacheService = cacheService;
}

public Object invoke(MethodInvocation invocation) throws Throwable {
Object result = cacheServiceget(cacheKey);
//如果函数返回结果不在Cache中,执行函数并将结果放入Cache
if (result == null) {
result = invocationproceed();
cacheServiceput(cacheKey,result);
}
return result;
}
}
Spring的AOP配置如下:
Java代码
<aop:config proxy-target-class="true">
<aop:advisor
pointcut="execution( ×××PoiServicegetOne())"
advice-ref="PoiServiceCachingAdvice" />
aop:config>

<bean id="BasPoiServiceCachingAdvice"
class="×××corecacheCachingInterceptor">
<property name="cacheKey" value="PoiService" />
<property name="cacheService" ref="cacheService" />
bean>

配置修改:如果不懂代码的话,不要伸手,后果自负。
负载状态:memcached运行中的相关状态。其中最重要的是hit这个参数,也就是命中率。当然是越高越好了。
性能调整:前面IP和端口不要改。缓存大小根据实际情况调整。根据什么来调整呢?回到负载状态栏,有一个“当前已使用内存”,看这个数字来调整。比如默认分配给memcached一共64M内存,但是已使用内存62M就说明memcached可用内存快要满了,这时候就手动改大一点,比如128M。具体数字根据每天流量情况来定。
Memcached的目的就是把所有文章内容都扔进内存,这样用户来访时直接读取内存中的内容,跳过了数据库,所以使用memcached后网站打开感觉特别快。比如网站每天发几十篇文章,可能这个数字就调整大一点,防止不够用了


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/13380900.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-07-25
下一篇 2023-07-25

发表评论

登录后才能评论

评论列表(0条)

保存