ITeye博客

Spring调用spymemcached客户端的例子

Alex_hyts · 2016-05-06 16:01 · 企业架构 · Markdown

转载:Spring调用spymemcached客户端的例子

spymemcached客户端API:spymemcached client 
网址:http://code.google.com/p/spymemcached/ 

建立一个Client类来获得MemcachedClient的实例: 
Client.java 

Java代码  收藏代码

  1. package bcndyl.test;
  2. import java.io.IOException;
  3. import net.spy.memcached.AddrUtil;
  4. import net.spy.memcached.MemcachedClient;
  5. public class Client {
  6. private String str;
  7. public String getStr() {
  8. return str;
  9. }
  10. public void setStr(String str) {
  11. this.str = str;
  12. }
  13. public MemcachedClient getMClient() throws IOException{
  14. return new MemcachedClient(AddrUtil.getAddresses(str));
  15. }
  16. }

建立操作memcached的测试类: 
StringTest.java 

Java代码  收藏代码

  1. package bcndyl.test;
  2. import net.spy.memcached.MemcachedClient;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.FileSystemXmlApplicationContext;
  5. public class StringTest {
  6. public static void main(String[] args) throws Exception{
  7. ApplicationContext ctx=new FileSystemXmlApplicationContext("src/applicationContext.xml");
  8. for(int i=0; i<250; i++){
  9. Client b = (Client)ctx.getBean("client");
  10. MemcachedClient mc = b.getMClient();
  11. mc.set("key"+i, 3600, "hello");
  12. }
  13. }
  14. }

spring的配置文件为: 

Xml代码  收藏代码

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
  6. <bean id="client" class="bcndyl.test.Client">
  7. <property name="str">
  8. <value>192.168.227.20:12111</value>
  9. </property>
  10. </bean>
  11. </beans>

配置中不是向程序中直接注入MemcachedClient,而是通过向Client类中注入memcached服务器地址的方式之后再new出来一个MemcachedClient,如果有多个memcached服务器就输入多个地址的String值(如:“192.168.227.20:12111 192.168.227.21:12111”),不知道这样写符不符合spring的思想。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。