---
title: "Spring调用spymemcached客户端的例子"
author: "Alex_hyts"
date: "2016-05-06T16:01:46Z"
tags: []
categories: ["企业架构"]
slug: "spring-spymemcached"
draft: false
lastmod: "2016-05-06T16:01:46Z"
id: 2296359
url: "https://alex4java.iteye.com/blog/2296359"
---

### 转载：[Spring调用spymemcached客户端的例子](http://lveyo.iteye.com/blog/246305)

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

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

Java代码  [![收藏代码](http://lveyo.iteye.com/images/icon_star.png)]()

01. package bcndyl.test;
02. import java.io.IOException;
03. import net.spy.memcached.AddrUtil;
04. import net.spy.memcached.MemcachedClient;
05. public class Client {
06. private String str;
07. public String getStr() {
08. return str;
09. }
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代码  [![收藏代码](http://lveyo.iteye.com/images/icon_star.png)]()

01. package bcndyl.test;
02. import net.spy.memcached.MemcachedClient;
03. import org.springframework.context.ApplicationContext;
04. import org.springframework.context.support.FileSystemXmlApplicationContext;
05. public class StringTest {
06. public static void main(String\[] args) throws Exception{
07. ApplicationContext ctx=new FileSystemXmlApplicationContext("src/applicationContext.xml");
08. for(int i=0; i&lt;250; i++){
09. Client b = (Client)ctx.getBean("client");
10. MemcachedClient mc = b.getMClient();
11. mc.set("key"+i, 3600, "hello");
12. }
13. }
14. }

spring的配置文件为： 

Xml代码  [![收藏代码](http://lveyo.iteye.com/images/icon_star.png)]()

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;beans
03. xmlns="http://www.springframework.org/schema/beans"
04. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
05. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"&gt;
06. &lt;bean id="client" class="bcndyl.test.Client"&gt;
07. &lt;property name="str"&gt;
08. &lt;value&gt;192.168.227.20:12111&lt;/value&gt;
09. &lt;/property&gt;
10. &lt;/bean&gt;
11. &lt;/beans&gt;

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