spring整合redis

这里来记录下我整合的spring与redis

      jar包,我这里是自己用maven管理

<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.4.4.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.4.2</version>
		</dependency>

配置spring-redis.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: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">  
  
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
       <property name="minIdle" value="100" />  
       <property name="maxIdle" value="300" />    
       <property name="maxTotal" value="1000" />    
       <property name="testOnBorrow" value="true" />
    </bean>  
      
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
       <property name="hostName" value="localhost" />  
       <property name="usePool" value="true" />  
       <property name="poolConfig" ref="poolConfig" />
    </bean>
      
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
        <property name="connectionFactory"   ref="connectionFactory" />  
    </bean>         
</beans> 
编写baseDao类

package com.asiainfo.springmvc.redis.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

public class RedisBaseDao {
	
	@Autowired
	private RedisTemplate redisTemplate;    

	public RedisTemplate getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
	
	protected RedisSerializer getStringSerializer() {
		return redisTemplate.getStringSerializer();
		
	}
	
	protected RedisSerializer getHashValueSerializer() {
		return redisTemplate.getHashValueSerializer();
		
	}
	 
	 
}
这里存入redis的key value都经过了序列化与反序列化

   编写redis的服务类

package com.asiainfo.springmvc.redis.impl;

import java.util.ArrayList;
import java.util.List;

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.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Repository;

import com.asiainfo.springmvc.pojo.User;
import com.asiainfo.springmvc.redis.interfaces.IRedisDAO;


@Repository("redisDao")
public class RedisDaoImpl extends RedisBaseDao implements IRedisDAO{
	/**
	 * 将用户信息加入到缓存中
	 * @param users
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public boolean addInfoToRedisByAll(final String product,final List<User> users){
		Boolean flag = (Boolean) getRedisTemplate().execute(new RedisCallback<Boolean>() {
			public Boolean doInRedis(RedisConnection connection)
					throws DataAccessException {
				JdkSerializationRedisSerializer redisSerializer = (JdkSerializationRedisSerializer) getHashValueSerializer();
				for(User user:users){
					byte[] key = redisSerializer.serialize(product);
					byte[] value = redisSerializer.serialize(user);
					 connection.lPush(key, value);
				}
				return true;
				
			}
		});
		return flag;
	}
	
	@SuppressWarnings("unchecked")
	public boolean addInfoToRedisByOne(final List<User> users){
		Boolean flag = (Boolean) getRedisTemplate().execute(new RedisCallback<Boolean>() {
			public Boolean doInRedis(RedisConnection connection)
					throws DataAccessException {
				JdkSerializationRedisSerializer redisSerializer = (JdkSerializationRedisSerializer) getHashValueSerializer();
				for(User user:users){
					byte[] key = redisSerializer.serialize(user.getId());
					byte[] value = redisSerializer.serialize(user);
					 connection.set(key, value);
				}
				return true;
				
			}
		});
		return flag;
	}
	
    /**
     * 删除缓存中的key
     * @param userId
     */
	@SuppressWarnings("unchecked")
	public void delInfoToRedis(final int userId){
		Boolean flag = (Boolean)getRedisTemplate().execute(new RedisCallback<Boolean>() {
			public Boolean doInRedis(RedisConnection connection)
					throws DataAccessException {
				JdkSerializationRedisSerializer redisSerializer = (JdkSerializationRedisSerializer)getHashValueSerializer();
				byte[] key = redisSerializer.serialize(userId);
				connection.del(key);
				return true;
			}
		});
	}
	
    /**
     * 修改缓存中的值
     */
	@SuppressWarnings("unchecked")
	public boolean updateInfoToRedis(final User user){
		Boolean flag = (Boolean)getRedisTemplate().execute(new RedisCallback<Boolean>() {
			public Boolean doInRedis(RedisConnection connection)
					throws DataAccessException {
				JdkSerializationRedisSerializer redisSerializer = (JdkSerializationRedisSerializer)getHashValueSerializer();
				byte[] key = redisSerializer.serialize(user.getId());
				byte[] value = redisSerializer.serialize(user);
				connection.set(key, value);
				return true;
				
			}
		});
		return flag;
	}
	
	@SuppressWarnings("unchecked")
	public User queryInfoFromRedis(final int userId){
		User user =(User) getRedisTemplate().execute(new RedisCallback<User>() {
			public User doInRedis(RedisConnection connection)
					throws DataAccessException {
				JdkSerializationRedisSerializer redisSerializer = (JdkSerializationRedisSerializer)getHashValueSerializer();
				byte[] key = redisSerializer.serialize(userId);
				byte[] value = connection.get(key);
				User user = (User)redisSerializer.deserialize(value);
				return user;
			}
		});
		return user;
	}
	
	
	public List<User> queryInfoFromRedisByPage(final String userKey,final int startIndex,final int pageSize){
		@SuppressWarnings("unchecked")
		List<User> user =(List<User>) getRedisTemplate().execute(new RedisCallback<List<User>>() {
			public List<User> doInRedis(RedisConnection connection)
					throws DataAccessException {
				List<User> resultList = new ArrayList<User>();
				JdkSerializationRedisSerializer redisSerializer = (JdkSerializationRedisSerializer)getHashValueSerializer();
				byte[] key = redisSerializer.serialize(userKey);
				List<byte[]> list = connection.lRange(key, startIndex-1, startIndex+pageSize-2);
				for(byte[] b :list){
					User user = (User)redisSerializer.deserialize(b);
					resultList.add(user);
				}
				
				return resultList;
			}
		});
		return user;
	}
	
	@SuppressWarnings("unchecked")
	public void delAllInfoToRedis(final String userKey){
		Boolean flag = (Boolean)getRedisTemplate().execute(new RedisCallback<Boolean>() {
			public Boolean doInRedis(RedisConnection connection)
					throws DataAccessException {
				JdkSerializationRedisSerializer redisSerializer = (JdkSerializationRedisSerializer)getHashValueSerializer();
				byte[] key = redisSerializer.serialize(userKey);
				connection.del(key);
				return true;
			}
		});
	}
}
经过测试,已经整合完毕,当然在测试的时候,要开启服务端!,不然会报错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值