今天一位兄弟看了之前介绍Simple-Spring-Memcached文章后,向我咨询如何使用Simple-Spring-Memcached的问题。在解答他的一些疑问后,觉得有必要写一篇文章介绍一下在自己的项目中如何配置Simple-Spring-Memcached。为了写这篇文章,尝试Simple-Spring-Memcached的一些新的配置,比如使用json序列化Java对象。
要使用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(xing.hu@360hqb.com)
* 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后结果如下:
star@star: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
