要使用Simple-Spring-Memcached首先需要确認使用哪種memcached用戶端,在這裡将使用XMemcached。第一步,将依賴jar導入項目中,推薦使用maven。具體的依賴可以參照SSM源碼的pom.xml配置。具體步驟如下
1、建立一個maven項目,在pom.xml添加上Simple-Spring-Memcached的依賴,還有其它Spring,aop,Xmemcached等如下:
<dependency>
<groupId>com.googlecode.xmemcached</groupId>
<artifactId>xmemcached</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>r09</version>
</dependency>
<dependency>
<groupId>com.google.code.simple-spring-memcached</groupId>
<artifactId>simple-spring-memcached</artifactId>
<version>2.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.3</version>
</dependency>
2、在src/main/resources目錄下增加spring的配置檔案,其中一個為xmemcached的配置檔案,一個為spring主配置檔案。如下:
context.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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<import resource="simplesm-context.xml" />
<aop:aspectj-autoproxy />
<context:annotation-config />
<context:component-scan base-package="com.google.code.ssm,org.colorfuldays.ssm" />
<import resource="xmemcached.xml"/>
</beans>
xmemcached.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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<aop:aspectj-autoproxy/>
<bean name="defaultMemcachedClient" class="com.google.code.ssm.CacheFactory">
<property name="cacheClientFactory">
<bean class="com.google.code.ssm.providers.xmemcached.MemcacheClientFactoryImpl"/>
</property>
<property name="addressProvider">
<bean class="com.google.code.ssm.config.DefaultAddressProvider">
<property name="address" value="127.0.0.1:11211"/>
</bean>
</property>
<property name="configuration">
<bean class="com.google.code.ssm.providers.CacheConfiguration">
<property name="consistentHashing" value="true"/>
</bean>
</property>
<property name="cacheTranscoders">
<map>
<entry key="org.colorfuldays.ssm.domain.UserDO" value-ref="jsonTranscoder"/>
</map>
</property>
</bean>
<bean name="jsonTranscoder" class="com.google.code.ssm.transcoders.JsonTranscoder">
<constructor-arg index="0" value="org.colorfuldays.ssm.domain.UserDO"/>
<constructor-arg index="1">
<ref bean="JsonObjectMapper"/>
</constructor-arg>
<constructor-arg index="2">
<ref bean="longToStringTranscoder"/>
</constructor-arg>
</bean>
<bean name="longToStringTranscoder" class="com.google.code.ssm.transcoders.LongToStringTranscoder"/>
<bean name="JsonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper"/>
</beans>
這兩個配置檔案與官方源碼中提供的測試例子差别不大,隻是多出了Transcoder的配置。在配置TransCoder時,要注意JsonTranscoder隻能通過構造函數注入。cacheTranscoders的配置中需要注意其key為Class對象。
完成上述配置後,寫個簡單的例子測試。測試代碼如下:
TestNG測試類
package org.colorfuldays.ssm.dao;
import junit.framework.Assert;
import org.codehaus.jackson.map.ObjectMapper;
import org.colorfuldays.ssm.domain.UserDO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* Created by IntelliJ IDEA.
* User: huxing(huxing1985#gmail.com)
* Date: 12-5-18
* Time: 下午6:14
*/
@ContextConfiguration(locations = {"classpath:context.xml"})
public class UserDAOTest extends AbstractTestNGSpringContextTests {
private static final Logger LOG = LoggerFactory.getLogger(UserDAOTest.class);
@Resource
UserDAO userDAO;
UserDO orignUserDO;
@BeforeTest
public void before() {
orignUserDO = new UserDO();
orignUserDO.setId(1024l);
orignUserDO.setName("Inzaghi");
orignUserDO.setPassword("password");
}
@Test
public void testGetUserById() throws Exception {
UserDO userDO = userDAO.getUserById(1124);
System.out.println(userDO);
Assert.assertTrue(orignUserDO.equals(userDO));
}
@Test
public void testUpdateUserDO() throws Exception {
}
}
DAOImpl類
package org.colorfuldays.ssm.dao.impl;
import com.google.code.ssm.api.InvalidateSingleCache;
import com.google.code.ssm.api.ParameterValueKeyProvider;
import com.google.code.ssm.api.ReadThroughSingleCache;
import com.google.code.ssm.api.format.UseJson;
import org.colorfuldays.ssm.dao.UserDAO;
import org.colorfuldays.ssm.domain.UserDO;
import org.springframework.stereotype.Repository;
/**
* Created by IntelliJ IDEA.
* User: huxing(huxing1985#gmail.com)
* Date: 12-5-18
* Time: 下午5:50
*/
@Repository("userDAO")
public class UserDAOImpl implements UserDAO {
@Override
@UseJson // 以json格式序列化
@ReadThroughSingleCache(namespace = "star",expiration = 30)
public UserDO getUserById(@ParameterValueKeyProvider long id) {
UserDO userDO = new UserDO();
userDO.setId(1024l);
userDO.setName("Inzaghi");
userDO.setPassword("password");
return userDO;
}
@Override
public int updateUserDO(UserDO userDO) {
return 0;
}
@InvalidateSingleCache(namespace = "star")
public int deleteUser(@ParameterValueKeyProvider long userId) {
return 0;
}
}
package org.colorfuldays.ssm.domain;
import java.io.Serializable;
/**
* Created by IntelliJ IDEA.
* User: huxing([email protected])
* Date: 12-5-18
* Time: 下午5:44
*/
public class UserDO implements Serializable{
private static final long serialVersionUID = -9096141633317522945L;
private String name;
private Long id;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "UserDO{" +
"name='" + name + '\'' +
", id=" + id +
", password='" + password + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UserDO)) return false;
UserDO userDO = (UserDO) o;
if (id != null ? !id.equals(userDO.id) : userDO.id != null) return false;
if (name != null ? !name.equals(userDO.name) : userDO.name != null) return false;
if (password != null ? !password.equals(userDO.password) : userDO.password != null) return false;
return true;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (id != null ? id.hashCode() : 0);
result = 31 * result + (password != null ? password.hashCode() : 0);
return result;
}
}
啟動memcached後即可運作單元測試了。其中使用了@UseJson的注解指定使用json格式對對象做序列化。通過下面的方式可以看到對象存入memcached後結果如下:
[email protected]:simple-spring-memcached-read-only$ telnet 127.0.0.1 11211
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
get star:1124
END
get star:1124
VALUE star:1124 8 50
{"name":"Inzaghi","id":1024,"password":"password"}
END
如果不使用@UseJson注解,則存入Memcached的資料則是Java預設序列化的資料。
測試代碼在這裡: https://github.com/iamxhu/ssm-demo