Java使用memcache示例

来源:互联网 发布:tracert 路由节点优化 编辑:程序博客网 时间:2024/05/02 00:26

    许多Web应用都将数据保存到RDBMS中,应用服务器从中读取数据并在浏览器中显示。 但随着数据量的增大、访问的集中,就会出现RDBMS的负担加重、数据库响应恶化、 网站显示延迟等重大影响。

这时就该memcached大显身手了。memcached是高性能的分布式内存缓存服务器。 一般的使用目的是,通过缓存数据库查询结果,减少数据库访问次数,以提高动态Web应用的速度、 提高可扩展性。

wKioL1bSZ0SyGE9HAABwpxMDqmk727.png


Windows系统下memcache的安装

cmd进入到memcache目录下(win10需要以管理员身份运行cmd)

wKiom1bNe2Cx42PGAAApgb_2llw067.png

memcache.exe -d install

memcache.exe -d start

启动memcache服务后可以在windows服务中看到名称为memcache 的服务


Java使用memcache

项目目录如下

wKiom1bNewzyQqotAABhndBm_zg860.png

User.java

public class User implements Serializable{    private static final long serialVersionUID = 1L;    private String username;         private String password;    //省略构造函数级getter setter            @Override    public int hashCode() {        final int prime = 31;        int result = 1;        result = prime * result                + ((password == null) ? 0 : password.hashCode());        result = prime * result                + ((username == null) ? 0 : username.hashCode());        return result;    }     @Override    public boolean equals(Object obj) {        if (this == obj)            return true;        if (obj == null)            return false;        if (getClass() != obj.getClass())            return false;        User other = (User) obj;        if (password == null) {            if (other.password != null)                return false;        } else if (!password.equals(other.password))            return false;        if (username == null) {            if (other.username != null)                return false;        } else if (!username.equals(other.username))            return false;        return true;    }}


MemcachedUtil.java

public class MemcachedUtil {    /**     * memcached客户端单例     */    private static MemCachedClient cachedClient = new MemCachedClient();    /**     * 初始化连接池     */    static {        //获取连接池的实例        SockIOPool pool = SockIOPool.getInstance();                 //服务器列表及其权重        String[] servers = {"127.0.0.1:11211"};        Integer[] weights = {3};                 //设置服务器信息        pool.setServers(servers);        pool.setWeights(weights);                 //设置初始连接数、最小连接数、最大连接数、最大处理时间        pool.setInitConn(10);        pool.setMinConn(10);        pool.setMaxConn(1000);        pool.setMaxIdle(1000*60*60);                 //设置连接池守护线程的睡眠时间        pool.setMaintSleep(60);                 //设置TCP参数,连接超时        pool.setNagle(false);        pool.setSocketTO(60);        pool.setSocketConnectTO(0);                 //初始化并启动连接池        pool.initialize();                 //压缩设置,超过指定大小的都压缩//      cachedClient.setCompressEnable(true);//      cachedClient.setCompressThreshold(1024*1024);    }         private MemcachedUtil(){    }         public static boolean add(String key, Object value) {        return cachedClient.add(key, value);    }         public static boolean add(String key, Object value, Integer expire) {        return cachedClient.add(key, value, expire);    }         public static boolean put(String key, Object value) {        return cachedClient.set(key, value);    }         public static boolean put(String key, Object value, Integer expire) {        return cachedClient.set(key, value, expire);    }         public static boolean replace(String key, Object value) {        return cachedClient.replace(key, value);    }         public static boolean replace(String key, Object value, Integer expire) {        return cachedClient.replace(key, value, expire);    }         public static Object get(String key) {        return cachedClient.get(key);    }}


MemcachedUtilTest.java测试类

public class MemcachedUtilTest {    @Test    public void testMemcached() {        MemcachedUtil.put("hello", "world", 60);        String hello = (String) MemcachedUtil.get("hello");        Assert.assertEquals("world", hello);                 for(int i = 0; i < 10000; ++i) {            User user = new User("Jason" + i, "123456-" + i);            MemcachedUtil.put("user" + i, user, 60);            Object obj = MemcachedUtil.get("user" + i);            Assert.assertEquals(user, obj);        }    }}


在Spring中配置并使用memcache

applicationContext.xml配置文件

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans           http://www.springframework.org/schema/beans/spring-beans.xsd">     <bean id="memcachedPool" class="com.danga.MemCached.SockIOPool"        factory-method="getInstance" init-method="initialize">        <constructor-arg>            <value>neeaMemcachedPool</value>        </constructor-arg>        <property name="servers">            <list>                <value>127.0.0.1:11211</value>            </list>        </property>        <property name="initConn">            <value>20</value>        </property>        <property name="minConn">            <value>10</value>        </property>        <property name="maxConn">            <value>50</value>        </property>        <property name="nagle">            <value>false</value>        </property>        <property name="socketTO">            <value>3000</value>        </property>    </bean>    <bean id="memcachedClient" class="com.danga.MemCached.MemCachedClient">        <constructor-arg>            <value>neeaMemcachedPool</value>        </constructor-arg>    </bean></beans>


MemcachedSpringTest.java测试类

public class MemcachedSpringTest {    private MemCachedClient cachedClient;        @Before    public void init() {        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");        cachedClient = (MemCachedClient)context.getBean("memcachedClient");    }         @Test    public void testMemcachedSpring() {        User user = new User("lou", "jason");        cachedClient.set("user", user);        User cachedBean = (User)user;        Assert.assertEquals(user, cachedBean);    }}


本机测试全部通过

本文出自 “优赛工作室” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1744728

0 0
原创粉丝点击