• spring 整合redis


    用的是最新的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等注解。

  • 相关阅读:
    2019牛客暑期多校训练营(第六场)
    2019牛客暑期多校训练营(第五场)
    2019牛客暑期多校训练营(第四场)
    2019牛客暑期多校训练营(第三场)
    Codeforces Round #554 (Div. 2) C. Neko does Maths (数论 GCD(a,b) = GCD(a,b-a))
    Codeforces Round #486 (Div. 3) C "Equal Sums" (map+pair<>)
    Count New String
    【模板】后缀自动机 (SAM)
    Watchcow
    二次剩余
  • 原文地址:https://www.cnblogs.com/hjy9420/p/4278002.html
Copyright © 2020-2023  润新知