欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring与Redis整合 博客分类: SpringRedis redisspring-data-redis 

程序员文章站 2024-03-21 23:36:40
...

commons-lang3-3.1.jar

spring-data-commons-1.11.0.jar

spring-data-redis-1.6.1.jar

jedis-2.6.0.jar

spring-XX-4.0.6.jar

 

在spring的beans.xml中添加:

    <!-- 对象池 -->
    <bean id="jedisPoolConfig" 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="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  
        <property name="hostName" value="${redis.host}" />  
        <property name="port" value="${redis.port}" />   
        <!-- <property name="password" value="${redis.pass}" />  -->  
        <property name="poolConfig" ref="jedisPoolConfig" />  
    </bean>  

    <!-- 模板类 --> 
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
        <property name="connectionFactory" ref="jedisConnectionFactory"/>
        <property name="keySerializer">
        	<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
        </property>
        <property name="valueSerializer"> <!-- default:JdkSerializationRedisSerializer -->
        	<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"></bean>
        </property>
    </bean>

 

service实现层:

package com.edus.service.impl.demo;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.edus.entity.Book;
import com.edus.service.demo.IRedisDemoService;

@Service("redisDemoService")
public class RedisDemoServiceImpl implements IRedisDemoService {

	@Resource
    private RedisTemplate<Serializable, Serializable> redisTemplate;

	private static String PREFIX_USER = "book:";
	
	
	@Override
	public void delBookInRedis(Integer id) {
		redisTemplate.opsForHash().delete(PREFIX_USER+id, id);
	}

	@Override
	public Book getBookFromRedis(final Integer id) {
//		redisTemplate.multi();
//		redisTemplate.opsForHash().put(PREFIX_USER+id, "id", id);
		Book book = (Book)redisTemplate.opsForHash().get(PREFIX_USER+id, id);
//		System.out.println(book);
//		redisTemplate.exec();
		return book;
	}

	@Override
	public void saveOrUpdateBookInRedis(final Book book) {
//		System.out.println("1xxxx="+redisTemplate.getConnectionFactory().getClass().getName());
//		System.out.println("1default="+redisTemplate.getDefaultSerializer().getClass().getName());
//		System.out.println("1key="+redisTemplate.getKeySerializer().getClass().getName());
//		System.out.println("1value="+redisTemplate.getValueSerializer().getClass().getName());
		
		//开启事务
//		redisTemplate.multi();
		redisTemplate.opsForHash().put(PREFIX_USER+book.getId(), book.getId(), book);
//		redisTemplate.exec();
		
		
	}

	@Override
	public Set<Book> findBookListInRedis(Map<String, Object> args) {
		Set<Serializable> keySet = redisTemplate.keys(PREFIX_USER+"*");
		Set<Book> resultSet = new HashSet<Book>();
		for(Object key : keySet) {
			Integer id = Integer.parseInt(key.toString().split(":")[1]);
        	Book book = getBookFromRedis(id);
        	resultSet.add(book);
			System.out.println(book);
		}
		return resultSet;
	}
    
}

 

 或:

package com.edus.service.impl.demo;

import java.io.Serializable;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import com.edus.entity.Book;
import com.edus.service.demo.IRedisDemoService;

@Service("redisDemoService")
public class RedisDemoServiceImpl implements IRedisDemoService {

	@Resource
    protected RedisTemplate<Serializable, Serializable> redisTemplate;
	
	@Override
	public void delBookInRedis(final Integer id) {
		redisTemplate.execute(new RedisCallback<Object>() {  
	        @Override  
	        public Object doInRedis(RedisConnection connection) {  
	            connection.del(redisTemplate.getStringSerializer().serialize("book.id." + id)); 
	            connection.del(redisTemplate.getStringSerializer().serialize("book.price." + id)); 
	            connection.del(redisTemplate.getStringSerializer().serialize("book.name." + id)); 
	            return null;  
	        }  
	    });
	}

	@Override
	public Book findOneBookInRedis(final Integer id) {
		return redisTemplate.execute(new RedisCallback<Book>() {  
	        @Override  
	        public Book doInRedis(RedisConnection connection)  
	                throws DataAccessException {  
	            byte[] bid = redisTemplate.getStringSerializer().serialize(  
	                    "book.id." + id);  
	            if (connection.exists(bid)) {  
	            	byte[] nameByte = redisTemplate.getStringSerializer().serialize(  
		                    "book.name." + id);
	                byte[] nameVal = connection.get(nameByte);  
	                String name = redisTemplate.getStringSerializer().deserialize(nameVal); 

	                byte[] priceByte = redisTemplate.getStringSerializer().serialize(  
		                    "book.price." + id);
	                byte[] priceVal = connection.get(priceByte);  
	                String price = redisTemplate.getStringSerializer().deserialize(priceVal); 
	                
	                Book book = new Book();
	                book.setId(id);
	                book.setName(name);
	                book.setPrice(Double.parseDouble(price));
	                return book;  
	            }  
	            return null;  
	        }  
	    });  
	}

	@Override
	public boolean  saveBookInRedis(final Book book) {
		return redisTemplate.execute(new RedisCallback<Boolean>() {  
	        @Override  
	        public Boolean doInRedis(RedisConnection connection)  
	                throws DataAccessException {  
	        	//connection.hSet(arg0, arg1, arg2)
	            connection.set(  
	                    redisTemplate.getStringSerializer().serialize( "book.id." + book.getId()),  
	                    redisTemplate.getStringSerializer().serialize( String.valueOf(book.getId()))); 
	            connection.set(  
	                    redisTemplate.getStringSerializer().serialize( "book.name." + book.getId()),  
	                    redisTemplate.getStringSerializer().serialize( book.getName()));
	            connection.set(  
	                    redisTemplate.getStringSerializer().serialize( "book.price." + book.getId()),  
	                    redisTemplate.getStringSerializer().serialize( String.valueOf(book.getPrice()))); 
	            return true;  
	        }  
	    }); 
	}

	@Override
	public boolean updateBookInRedis(final Book book) {
		Integer key = book.getId();  
        if (this.findOneBookInRedis(key) == null) {  
            throw new NullPointerException("数据行不存在, book.id = " + key);  
        }  
        return redisTemplate.execute(new RedisCallback<Boolean>() {  
            public Boolean doInRedis(RedisConnection connection)  
                    throws DataAccessException {  
//            	if(book.getName() != null && book.getName().length() > 0) {
	                byte[] key  = redisTemplate.getStringSerializer().serialize("book.name."+String.valueOf(book.getId()));  
	                byte[] name = redisTemplate.getStringSerializer().serialize(book.getName());  
	                connection.set(key, name);  
//            	}
            	if(book.getPrice() != null) {
	                byte[] key  = redisTemplate.getStringSerializer().serialize("book.name."+String.valueOf(book.getId()));  
	                byte[] name = redisTemplate.getStringSerializer().serialize(book.getName());  
	                connection.set(key, name);  
            	}
                return true;  
            }  
        });  
	}    
}