来源:http://blog.csdn.net/u013142781/article/details/50515320
一、pom添加依赖
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.7.2.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.0</version> </dependency>
二、spring配置文件
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:redis.properties" /> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="${redis.maxIdle}" /> <property name="maxActive" value="${redis.maxActive}" /> <property name="maxWait" value="${redis.maxWait}" /> <property name="testOnBorrow" value="${redis.testOnBorrow}" /> </bean> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/> <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"> <property name="connectionFactory" ref="connectionFactory" /> </bean> <bean id="userDao" class="com.x.dao.impl.UserDao" /> </beans>
三、redis.properties
#redis绑定的主机地址 redis.host=127.0.0.1 #redis监听端口,默认6379 redis.port=6379 #redis授权密码 redis.password= #最大空闲数,空闲链接数大于maxIdle时,将进行回收 redis.maxIdle=100 #最大连接数,能够同时建立的“最大链接个数” redis.maxActive=300 #最大等待时间:单位ms redis.maxWait=1000 #使用连接时,检测连接是否成功 redis.testOnBorrow=true #当客户端闲置多长时间后关闭连接,如果指定为0,表示关闭该功能 redis.timeout=10000
四、entity类
package entity; import java.io.Serializable; /** * Created by mochou on 2016/9/6. */ public class User implements Serializable{ private static final long serialVersionUID = 6488670680273465614L; private String id; private String name; private String password; public User() { } public User(String id, String name, String password) { this.id = id; this.name = name; this.password = password; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
五、AbstractBaseRedisDao类
package dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.RedisSerializer; /** * Created by mochou on 2016/9/6. */ public abstract class AbstractBaseRadisDAO<K,V>{ @Autowired protected RedisTemplate<K,V> redisTemplate; public RedisSerializer<String> getRedisSerializer() { return redisTemplate.getStringSerializer(); } public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) { this.redisTemplate = redisTemplate; } }
六、IUserDao接口
package dao; import entity.User; import java.util.List; /** * Created by mochou on 2016/9/6. */ public interface IUserDao { //新增 boolean add(User user); //批量新增,使用pipeline方式 boolean add(List<User> users); //删除 void delete(String key); //批量删除 void delete(List<String> keys); //更新 boolean update(User user); //获取 User get(String keyId); }
七、DAO类
package dao.impl; import dao.AbstractBaseRadisDAO; import dao.IUserDao; import entity.User; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.util.Assert; import java.util.ArrayList; import java.util.List; /** * Created by mochou on 2016/9/6. */ public class UserDao extends AbstractBaseRadisDAO<String, User> implements IUserDao { @Override public boolean add(final User user) { boolean result=redisTemplate.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException { RedisSerializer redisSerializer=getRedisSerializer(); byte[] key=redisSerializer.serialize(user.getId()); byte[] name=redisSerializer.serialize(user.getName()); return redisConnection.setNX(key,name); } }); return result; } @Override public boolean add(final List<User> users) { Assert.notEmpty(users); boolean result=redisTemplate.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException { RedisSerializer<String> redisSerializer=getRedisSerializer(); for(User user:users){ byte[] key = redisSerializer.serialize(user.getId()); byte[] name = redisSerializer.serialize(user.getName()); redisConnection.setNX(key, name); } return true; } },false,true); return result; } @Override public void delete(String key) { List<String> list=new ArrayList<>(); list.add(key); delete(list); } @Override public void delete(List<String> keys) { redisTemplate.delete(keys); } @Override public boolean update(final User user) { String key=user.getId(); if(get(key)==null){ throw new NullPointerException("数据行不存在,key= "+key); } boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = getRedisSerializer(); byte[] key = serializer.serialize(user.getId()); byte[] name = serializer.serialize(user.getName()); connection.set(key, name); return true; } }); return result; } @Override public User get(final String keyId) { User result = redisTemplate.execute(new RedisCallback<User>() { public User doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = getRedisSerializer(); byte[] key = serializer.serialize(keyId); byte[] value = connection.get(key); if (value == null) { return null; } String name = serializer.deserialize(value); return new User(keyId, name, null); } }); return result; } }
八、编写测试类
import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import com.x.dao.IUserDao; import com.x.entity.User; /** * 测试 * @author http://blog.csdn.net/java2000_wl * @version <b>1.0</b> */ @ContextConfiguration(locations = {"classpath*:applicationContext.xml"}) public class RedisTest extends AbstractJUnit4SpringContextTests { @Autowired private IUserDao userDao; /** * 新增 * <br>------------------------------<br> */ @Test public void testAddUser() { User user = new User(); user.setId("user1"); user.setName("java2000_wl"); boolean result = userDao.add(user); Assert.assertTrue(result); } /** * 批量新增 普通方式 * <br>------------------------------<br> */ @Test public void testAddUsers1() { List<User> list = new ArrayList<User>(); for (int i = 10; i < 50000; i++) { User user = new User(); user.setId("user" + i); user.setName("java2000_wl" + i); list.add(user); } long begin = System.currentTimeMillis(); for (User user : list) { userDao.add(user); } System.out.println(System.currentTimeMillis() - begin); } /** * 批量新增 pipeline方式 * <br>------------------------------<br> */ @Test public void testAddUsers2() { List<User> list = new ArrayList<User>(); for (int i = 10; i < 1500000; i++) { User user = new User(); user.setId("user" + i); user.setName("java2000_wl" + i); list.add(user); } long begin = System.currentTimeMillis(); boolean result = userDao.add(list); System.out.println(System.currentTimeMillis() - begin); Assert.assertTrue(result); } /** * 修改 * <br>------------------------------<br> */ @Test public void testUpdate() { User user = new User(); user.setId("user1"); user.setName("new_password"); boolean result = userDao.update(user); Assert.assertTrue(result); } /** * 通过key删除单个 * <br>------------------------------<br> */ @Test public void testDelete() { String key = "user1"; userDao.delete(key); } /** * 批量删除 * <br>------------------------------<br> */ @Test public void testDeletes() { List<String> list = new ArrayList<String>(); for (int i = 0; i < 10; i++) { list.add("user" + i); } userDao.delete(list); } /** * 获取 * <br>------------------------------<br> */ @Test public void testGetUser() { String id = "user1"; User user = userDao.get(id); Assert.assertNotNull(user); Assert.assertEquals(user.getName(), "java2000_wl"); } /** * 设置userDao * @param userDao the userDao to set */ public void setUserDao(IUserDao userDao) { this.userDao = userDao; } }