Memcached struts2 java linux 简单例子

一、

Memcached安装和使用:
官网:http://monkey.org/~provos/libevent/
libevent
下载:http://monkey.org/~provos/libevent-1.4.9-stable.tar.gz
Memcached
官网:http://www.danga.com/memcached
Memcached
下载:http://www.danga.com/memcached/dist/memcached-1.2.6.tar.gz

二、

安装 libevent
# tar zxvf libevent-1.4.9-stable.tar.gz
# cd libevent-1.4.9-stable
# ./configure --prefix=/usr
# make
# make install

安装 Memcached
# tar zxvf memcached-1.2.6.tar.gz
# cd memcached-1.2.6
# ./configure --prefix=/usr/local
# make
# make install

三、

       安装成功启动

       ./memcached -d -u root -m 512 127.0.0.1 -p 11211

  到这里,看到memcached已经启动,说明安装成功。

  如果要结束Memcache进程,执行:

  # kill `cat /tmp/memcached.pid`

  也可以启动多个守护进程,不过端口不能重复。

  memcache启动参数说明:

  -d选项是启动一个守护进程,

  -m是分配给Memcache使用的内存数量,单位是MB,我这里是10MB,

  -u是运行Memcache的用户,我这里是root,

  -l是监听的服务器IP地址,如果有多个地址的话,我这里指定了服务器的IP地址192.168.0.200,

  -p是设置Memcache监听的端口,我这里设置了12000,最好是1024以上的端口,

  -c选项是最大运行的并发连接数,默认是1024,我这里设置了256,按照你服务器的负载量来设定,

  -P是设置保存Memcache的pid文件,我这里是保存在 /tmp/memcached.pid

四 、代码部分

1.MemCacheClient类

 

package com.uitl;

import java.util.Date;
import java.util.Map;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
/***
 * 
 * @author ZhuangZi
 * @version $Id: MemCacheClient.java,v 0.1 2013-3-5 下午04:35:56 ZhuangZi Exp $
 */
public class MemCacheClient {

	protected static MemCachedClient memcachedClient = new MemCachedClient();

	protected static String cacheIP = "192.168.3.27:11211";

	static {
		// 服务器列表和其权重,memcached地址和端口号
		String[] servers = { cacheIP };
		Integer[] weights = { 3 };
		// 获取socke连接池的实例对象
		SockIOPool pool = SockIOPool.getInstance();
		// 设置服务器信息
		pool.setServers(servers);
		pool.setWeights(weights);
		// 设置初始连接数、最小和最大连接数以及最大空闲时间
		pool.setInitConn(5);
		pool.setMinConn(5);
		pool.setMaxConn(500);
		pool.setMaxIdle(1000 * 60 * 60 * 6);
		// 设置主线程的睡眠时间秒
		pool.setMaintSleep(30);
		// 关闭nagle算法
		pool.setNagle(false);
		// 设置 读取 超时3秒钟
		pool.setSocketTO(3000);
		// 不设置连接超时
		pool.setSocketConnectTO(0);
		// 初始化一些值并与MemcachedServer段建立连接
		pool.initialize();
	}

	/***
	 * 读取缓存
	 * @param key
	 * @param times
	 * @return
	 */
	public static String getValue(String key, int times) {
		String value = "";
		try {
			value = memcachedClient.get(key, times).toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return value;
	}

	/***
	 * 设置缓存
	 * @param key
	 * @param value
	 * @param times
	 * @return
	 */
	public static boolean setValue(String key, String value, int times) {
		boolean result = false;
		try {
		    System.out.println("********");
			result = memcachedClient.set(key, value,
					new Date(System.currentTimeMillis() + times * 1000));
			  System.out.println("*1*******"+result);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return result;
	}

	public static boolean setValue(String key, String value) {
		boolean result = false;
		try {
			result = memcachedClient.set(key, value);
		} catch (Exception e) {
		    e.printStackTrace();
			return false;
		}
		return result;
	}

	/***
	 * 删除缓存
	 * @param key
	 * @return
	 */
	public static boolean delete(String key) {
		return memcachedClient.delete(key);
	}

	@SuppressWarnings("unchecked")
    public static Map getStatus() {
		Map stats = memcachedClient.stats();
		return stats;
	}

	public Object[] getMultiArray(String[] sKeys) {
		return memcachedClient.getMultiArray(sKeys);
	}

	public static void main(String[] args) {
//		 System.out.println(setValue("2", "密密麻麻",100));
//		System.out.println(getValue("2", 1));
		// delete("eventinfo_zd");"
		// PrizeObject prizeObject = new PrizeObject();
		// System.out.println();
		// prizeObject = JSON.parseObject(getValue("20120418180611", 1000),
		// PrizeObject.class);
		// System.out.println(prizeObject.getPrizeName());
		// System.out.println((int)(Math.random()*1000));
		// Map map = getStatus();
		// System.out.println("11");
	}
}


2.MemcachedeAction类

package com.action;

import com.opensymphony.xwork2.ActionSupport;
import com.uitl.MemCacheClient;
@SuppressWarnings("serial")
public class MemcachedeAction extends ActionSupport {
	private String s_str_key;
	private String s_str_value;
	private String g_str_key;
	private String g_str_value;
	public String memc() {
	    try {
	        if (s_str_value!=null&&!s_str_value.equals("")) {
	            System.out.println(s_str_key+"######"+s_str_value);
	            MemCacheClient.setValue(s_str_key, s_str_value);
            }else{
                s_str_value="";
                s_str_key="";
            }
	        
	        if(g_str_key!=null&&!g_str_key.equals("")){
	            g_str_value=MemCacheClient.getValue(g_str_key, 2000);
	            System.out.println("###########"+g_str_key+"="+g_str_value+"######################");
	        }else{
	            g_str_value="";
	            g_str_key="";
            }
	        
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
	
		return "success";
	}
    public String getS_str_key() {
        return s_str_key;
    }
    public void setS_str_key(String sStrKey) {
        s_str_key = sStrKey;
    }
    public String getS_str_value() {
        return s_str_value;
    }
    public void setS_str_value(String sStrValue) {
        s_str_value = sStrValue;
    }
    public String getG_str_key() {
        return g_str_key;
    }
    public void setG_str_key(String gStrKey) {
        g_str_key = gStrKey;
    }
    public String getG_str_value() {
        return g_str_value;
    }
    public void setG_str_value(String gStrValue) {
        g_str_value = gStrValue;
    }



}


3.struts配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC  "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="struts2"   extends="struts-default">
		<action name="memc" method="memc" class="com.action.MemcachedeAction">
			<result name="success">/index.jsp</result>
			<result name="input">/index.jsp</result>
		</action>
	</package>
</struts>


4.index.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
 	 <form action="memc.action" method="post" name="thisform"  >
 	   Set Memcached key:  
 	   <s:textfield name="s_str_key"></s:textfield> <BR/>
 	    Set Memcached value:  
 	   <s:textfield name="s_str_value"></s:textfield><BR/>
 	   <s:submit value="添加"></s:submit>
 	   
 	   
 	    
    </form>
    	 <form id="f1" action="memc.action" method="post" name="thisform"  >
 	   <s:submit value="查询"></s:submit>
 	    Get Memcached key: 
 	     <s:textfield name="g_str_key"></s:textfield>已经添加的key值有:a、b、c、d、e;<BR/>
 	      Get Memcached value: 
 	     <s:property value="g_str_value"/><BR/>
 	   
 	   
 	    
    </form>
  </body>
</html>

5.主要架包:

java_memcached-release_2.6.3.jar

slf4j-api-1.6.1.jar

slf4j-simple-1.6.1.jar

log4j-1.2.14.jar

commons-pool-1.5.2.jar
后续会附上demo

OK了,你就使劲顶贴吧 哈哈 给点发帖动力

你可能感兴趣的:(Memcached struts2 java linux 简单例子)