java调用处理 memcache

来源:互联网 发布:淘宝开店怎么发快递 编辑:程序博客网 时间:2024/06/12 10:10

1)memcache 内存设置:

装成服务之后,可以通过注册表修改命令设置最大内存。
位置在:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\memcached Server
修改ImagePath 的值为: “D:\memcached-1.2.6\memcached.exe” -m 128 -d runservice


2)java调用memcache:


package com.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
import com.SMSUitls;
import com.readLog;


public class MemcacheThread {
private final static Object stats = "{}"; 
private static Log log = LogFactory.getLog(MemcacheThread.class);
//代理
private final static MemCachedClient mcMem = new MemCachedClient();
private final static String serverMem = new ConfigBundle(new ConfigBundle().getWebInfPath()+ "WEB-INF/classes/server.properties").getString("memcahchePath");
private final static SockIOPool poolMem = SockIOPool.getInstance();
static{
try{
poolMem.setServers(new String[]{serverMem});
poolMem.setInitConn(2);
poolMem.setMinConn(2);
poolMem.setMaxConn(10);
poolMem.setMaxIdle(1000 * 60 * 60 * 6);
poolMem.setMaintSleep(30);
poolMem.setSocketTO(3000);
poolMem.initialize();
}catch(Exception e){
log.info("初始化连接代理缓存,发生异常的错误信息"+e.toString());
}
}
/***
* 插入緩存
 替換sql
  返回:
  0  异常
  1  正常
*/
public synchronized static int  insertMemCache(String code) {
StringBuffer logLine = new StringBuffer("");
MessageSend yf = MessageSend.getInstance();
yf.setCode(Code);
try {
//如果两个主 备 都挂了 就插入日志表
logLine =logLine.append("key==").append(NO).append("  ").
append("content==").append(content);
if(isMemHalt()){
readLog.writeFileB(logLine.toString(),"smsLog/beforeSet_isMemHalt.log");
return 0;
}else{
readLog.writeFileB(logLine.toString(),"smsLog/beforeSet.log");
if(mcMem.set(SEQNO, yf)){
readLog.writeFileB(logLine.toString(),"smsLog/afterSet_Success.log");
return 1;
}else{
readLog.writeFileB(logLine.toString(),"smsLog/afterSet_Fail.log");
return 0;
}
}
} catch (Exception e) {
log.info(e);
readLog.writeFileB(logLine.toString(),"smsLog/beforeSet_Exception.log");
FetionSend.getInstance().sendSMS("接口缓存可能挂掉了,快去看看吧",FetionSend.fetionSend_objMobile);
return 0;
}
}
public static String getFormatDate(Date date) throws ParseException {
SimpleDateFormat adf = new SimpleDateFormat("yyyyMMddHHmmssSS");
return adf.format(date);
}


public static String getHMS(Date date) throws ParseException {
SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return adf.format(date);
}


public static Date getDate(Date date) throws ParseException {
SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd");
return adf.parse(String.valueOf(date));
}


public static String todayStr() throws ParseException {
Date today = new Date();
return today.toString();
}


/**
* 缓存是否关闭
* @return
*/
public synchronized static boolean isMemHalt(){
//判断代理
try{
Map m = mcMem.stats();
int num=Integer.parseInt((((Map)m.get(serverMem)).get("curr_items").toString()).trim());
if(stats.equals(m.toString())){
log.info("状态===");
return true;
}
if(num>=SMSUitls.MEM_MAXNUM){
log.info("缓存满了===");
return true;
}
return false;
}catch(Exception e){
e.printStackTrace();
log.info("isMemHalt 方法中报错");
return true;
}
}
public static String getStringForRandom() {
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < 5; i++) {
int a;
for (a = (int) (100D * Math.random() + 100D * Math.random()); !((a > 10) & (a < 99)); a = (int) (100D * Math
.random() + 100D * Math.random())) {
}
sb.append(a);
}
System.out.println(sb.toString().substring(0, 7));
return sb.toString().substring(0, 7);
}



public static void main(String args[]) throws InterruptedException  {
// mcMem.set("1", "123");
// mcMem.set("1", "234");
isMemHalt();
}


public static int getAppSize(){
Map m = mcMem.stats();
      Iterator it = m.keySet().iterator();
while(it.hasNext()){
String e = (String)it.next().toString();
System.out.println(e);
Map m1 = (Map)m.get(e);
return Integer.parseInt(((String) m1.get("curr_items")).trim());
}
return 0;
}

}


三、安装Memcached及Memcached配置和状态查询 
          要想使用Memcached做缓存首先需要安装Memcached服务,安装方法如下: 
      1. 下载Memcached:http://code.jellycan.com/memcached/ 现在的最新版本是1.2.6.注意下载正确的版本,windows 服务的话下载win32 binary。 
      2.解压之后放在硬盘的目录下,如:D:\memcached. 然后在运行中输入cmd进入命令行,进入到Memcached.exe 所在的目录,例如:D:\memcached,然后输入:Memcached –d install,即可完成安装。 
          Memcached还有其他的一些常用的命令如下: 
      -p 监听的端口 
      -l 连接的IP地址, 默认是本机 
      -d start 启动memcached服务 
      -d restart 重起memcached服务 
      -d stop|shutdown 关闭正在运行的memcached服务 
      -d install 安装memcached服务 
      -d uninstall 卸载memcached服务 
      -u 以的身份运行 (仅在以root运行的时候有效) 
      -m 最大内存使用,单位MB。默认64MB 
      -M 内存耗尽时返回错误,而不是删除项 
      -c 最大同时连接数,默认是1024 
      -f 块大小增长因子,默认是1.25 
      -n 最小分配空间,key+value+flags默认是48 
      -h 显示帮助 
          按照上面的安装步骤安装之后,使用memcached –m 200来调整最大内存占用之后会发现没有起作用,总是默认的64MB的内存,在网上搜了一下,原因是注册表中并没有写入信息,可以这样来修改。 
         1. memcached –d shutdown 首先关闭memcached服务。 
         2.进入注册表,找到HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\memcached Server, 在其中有一个ImagePath项,值为"d:\memcached\memcached.exe" -d runservice,在后面加上-l 127.0.0.1 -m 3000 -c 2048。 
        3.memcached –d start 启动memcached服务,这样就将memcached的最大内存修改为了3000MB。 
        对Memcached缓存服务的状态查询,可以先telnet连接上服务:telnet 127.0.0.1 11211 ,然后使用 stats命令查看缓存服务的状态,会返回如下的数据:    
        time:    1255537291                               服务器当前的unix时间戳 
        total_items:    54                                     从服务器启动以后存储的items总数量 
        connection_structures:    19                    服务器分配的连接构造数 
        version:    1.2.6                                        memcache版本 
        limit_maxbytes:    67108864                    分配给memcache的内存大小(字节) 
        cmd_get:    1645                                      get命令(获取)总请求次数 
        evictions:    0                                            为获取空闲内存而删除的items数(分配给memcache的空间用满后需
                                                                         要删除旧的items来得到空间分配给新的items) 
        total_connections:    19                           从服务器启动以后曾经打开过的连接数 
        bytes:    248723                                      当前服务器存储items占用的字节数 
        threads:    1                                             当前线程数 
        get_misses:    82                                      总未命中次数 
        pointer_size:    32                                    当前操作系统的指针大小(32位系统一般是32bit) 
        bytes_read:    490982                              总读取字节数(请求字节数) 
        uptime:    161                                           服务器已经运行的秒数 
        curr_connections:    18                             当前打开着的连接数 
        pid:    2816                                               memcache服务器的进程ID 
        bytes_written:    16517259                     总发送字节数(结果字节数) 
        get_hits:    1563                                      总命中次数 
        cmd_set:    54                                          set命令(保存)总请求次数 
        curr_items:    28                                       服务器当前存储的items数量 

原创粉丝点击