码迷,mamicode.com
首页 > 编程语言 > 详细

spring 整合redis

时间:2015-02-06 21:37:59      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:

用的是最新的jedis-2.6.2.jar这个包,这个和以前的有点不同。还需要添加spring-data-redis-1.2.1.RELEASE.jar和commons-pool2-2.3.jar。

在类路径下创建spring-redis-config.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 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations" value="classpath:redis.properties"/>
    </bean>
     <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
        <property name="maxIdle" value="300" />  
        <property name="maxTotal" value="512" />  
        <property name="maxWaitMillis" value="1000" />  
        <property name="testOnBorrow" value="true" />  
    </bean>  
      
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
        p:host-name="localhost" p:port="6379" p:password=""  p:pool-config-ref="poolConfig"/>  
      
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
        <property name="connectionFactory"   ref="connectionFactory" />  
    </bean>         

  

</beans>

由于引用配置文件,使用不了表达式,这里写死了。使用表达式启动就报错,我也不知道为什么。

##
redis.host=localhost  
##
redis.port=6379
##  
redis.pass=  
  
##
redis.maxIdle=300
##  
redis.maxTotal=512
##
redis.maxWaitMillis=1000 
##
redis.testOnBorrow=true

redis.properties文件配置。

以前的版本应该有配置redis.maxActive但是看了源码,是没有setMaxActive方法的,所以不能注入,改用了redis.maxTotal。就因为这个弄了挺长时间的。

在web.xml配置spring-redis-config.xml文件

<context-param>
     <param-name>contextConfigLocation</param-name>
    <param-value>
                <!-- 多个配置用,隔开 -->
        
                classpath*:spring-redis-config.xml
                
    </param-value>
</context-param>

 

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

public abstract class AbstractBaseRedisDao<V, K> {

    @Autowired
    protected RedisTemplate<K, V> redisTemplate;
    
    public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {  
        this.redisTemplate = redisTemplate;  
    }  
      
    /** 
     * 获取 RedisSerializer 
     * <br>------------------------------<br> 
     */  
    protected RedisSerializer<String> getRedisSerializer() {  
        return redisTemplate.getStringSerializer();  
    }  
}

创建一个抽象类,然后让使用到的类都继承这个方法。

@Service("areaRedisService")
public class AreaRedisService<V, K> extends AbstractBaseRedisDao<V, K> {

    public boolean add(final Area area) {
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = getRedisSerializer();
                byte[] key = serializer.serialize(area.getId()+"");
                byte[] name = serializer.serialize(area.getName());
                return connection.setNX(key, name);
            }
        });
        return result;
    }
    
     public Area get(final String keyId) {  
         Area result = redisTemplate.execute(new RedisCallback<Area>() {  
                public Area 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 Area(Integer.valueOf(keyId),name,null);  
                }  
            });  
            return result;  
        }  
}

 

    @Autowired
    AreaRedisService<?, ?> areaRedisService;

    private String path = "/WEB-INF/jsp/";
    
    @RequestMapping("/area/redis.htm")
    public ModelAndView areaRedis(HttpServletRequest request, HttpServletResponse response,String name) throws Exception {
        ModelAndView mv = new ModelAndView(path+"add.html");
        Area area = new Area();
        area.setCreateTime(new Date());
        area.setCommon(true);
        area.setDeleteStatus(false);
        area.setLevel(4);
        area.setName(name);
        area.setParentId(null);
        area.setSequence(1);
                area.setId(1);
        areaRedisService.add(area);
        mv.addObject("area", area);
    mv.addObject("arearedis",areaRedisService.get(area.getId()+""));
        return mv;
        
        
    }        

这是controller的方法,这里使用了spring的注解。

使用注解,需要在上面的spring-redis-config.xml文件加入<context:component-scan base-package="基础包路径"/>配置了扫描路径可以不配置<context:annotation-config/>,因为前面的包含了后面的,他会激活@Controller,@Service,@Autowired,@Resource,@Component等注解。

spring 整合redis

标签:

原文地址:http://www.cnblogs.com/hjy9420/p/4278002.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!