Redis 存储List

1:Redis学习初级阶段,仅将redis如何存取List<Object>的简单实例分享如下。

 

2

(1)  修改配置文件application-redis.xml中的 redisTemplate 的属性, 添加该配置的作用是为了存储实体对象,将实体对象序列化后存储,否则就只能存储String的对象。

 

<property name="keySerializer" >
       <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
       <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property> 

 

 

(2)新增需要的实体类对象Address,该实体类必须实现序列化接口,目的嘛,你懂的。

 

/**
 * Address 地址实体类
 * @author zzs
 *
 */
public class Address implements Serializable {

	/**
	 * Address serialVersionUID
	 */
	private static final long serialVersionUID = 6654868162665356297L;

	private String  id;
	
	private String name;
	
	private String userId;//关联User的id

	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 getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}
	
}

 

 

 

(3)新增接口 IRedisSetAndListDao 

 

 

/**
 * Redis 的Set和List操作
 * @author zzs
 *
 */
public interface IRedisSetAndListDao {
	
	/**
	 * 新增addrList数据到内存库
	 * @param addrList
	 * @return
	 */
	public long addListAddress(List<Address> addrList);
	
}

 

 

(4)新增实现接口 RedisSetAndListDao

 

public class RedisSetAndListDao extends AbstractBaseRedisDao<String, Address > implements IRedisSetAndListDao 
{
	/**
	 * 新增addrList数据到内存库
	 * @param addrList
	 * @return
	 */
	public long addListAddress(List<Address> addrList) {
		Address[] addrArray = new Address[addrList.size()];
		for( int i = 0 ; i < addrList.size(); i++  ) {
			addrArray[i] = addrList.get(i);
		}
		long i = redisTemplate.opsForList().leftPushAll("addrList", addrArray);
		return i;
	}
	
}

 

 

(5)在application-redis.xml添加接口的注入配置

 

<bean id="redisSetAndListDao" class="redis.dao.impl.RedisSetAndListDao" />

 

 

(6)在你的测试类里面新增测试方法addListAddress

 

	/**
	 * 新增addrList数据到内存库
	 * @param addrList
	 * @return
	 */
	@Test
	public void addListAddress() {
		List<Address> addrList = new ArrayList<Address>();
		for( int i = 0; i < 8; i++ ){
			Address address = new Address();
			address.setId("address"+System.currentTimeMillis());
			address.setName("zhangzhisheng"+System.currentTimeMillis());
			address.setUserId("userId"+System.currentTimeMillis());
			addrList.add(address);
		}
		Long count = redisSetAndListDao.addListAddress(addrList);
	}

 

 

下次再见。

你可能感兴趣的:(object)