redisTemplate 操作


redisDao封裝類-其他dao集成他

package com.ffcs.wlan.dao.common;
import javax.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;

/** 
 * AbstractBaseRedisDao
 * @author hugsh
 * @version <b>1.0</b> 
 */ 
public abstract class AbstractBaseRedisDao<K, V> {
    
    @Resource
    protected StringRedisTemplate redisTemplate;

    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}

 批量插入(不關注返回值)

@Repository
public  class RedisInitDao extends AbstractBaseRedisDao<String, Object> {
        
    Logger logger=Logger.getLogger(RedisInitDao.class);
    
        /**
         * 批量向redis中插入H碼:key(tableName:hcode) value(pcode)
         * 如果鍵已存在則返回false,不更新,防止覆蓋。使用pipeline批處理方式(不關注返回值)
         *    @param list  一個map代表一行記錄,2個key:hcode & pcode。
         *    @param tableName redis中key的值為tableName:hcode  對應value值為pcode。
         *    @return
         */
        public boolean addHcode(final List<Map<String, Object>> list,final String tableName) {
            boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
                public Boolean doInRedis(RedisConnection connection)
                        throws DataAccessException {
                    RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                    for (Map<String, Object> map : list) {
                        byte[] key  = serializer.serialize(tableName+":"+map.get("hcode").toString());
                        byte[] name = serializer.serialize(map.get("pcode").toString());
                        connection.setNX(key, name);
                    }
                    return true;
                }
            }, false, true);
            return result;
        }
    

批量獲取(有返回值)

 

    /**
     * 從redis中獲取(獲取密碼日志) rPop從鏈表尾部彈出(最早的日志)
     * 多線程並發讀取日志長度的時候,比如都得到結果是1000條。
     * 當多線程每個都 循環1000次 pop彈出 日志的時候,
     * 由於是多線程一起pop,所以每個線程獲得的數組中都會包含 null  甚至有的全是null
     * @return
     */
    public List<String> getLogFromRedis() {
        
        final RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
        //密碼日志的長度
        final Long pwdLogSize=redisTemplate.opsForList().size("getpwdList");
        
        List<Object> pwdLogList=redisTemplate.executePipelined(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection conn)
                    throws DataAccessException {
                for (int i=0 ;i<pwdLogSize ;i++) {
                    byte[] listName  = serializer.serialize("getpwdList");
                    conn.rPop(listName);
                }
                return null;
            }
        }, serializer);
        
        //    去除結果中的null
        ArrayList<String> newList=new ArrayList<String>();
        for (Object o : pwdLogList) {
            if(o!=null)
                newList.add(String.valueOf(o));
        }
        return newList;
    }

 

基礎數據類型工具類(opsForList)

    /**
     * 向redis中插入獲取密碼日志:leftPush 從鏈表頭部壓入
     *    @param pwdLog 獲取密碼的日志
     *    @return
     */
    public void addLogIntoRedis(final String pwdLog) {
        log.info("insert getpwd log into redis:"+pwdLog);
        try {
            redisTemplate.opsForList().leftPush("getpwdList", pwdLog);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

配置文件

<?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: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="maxTotal" value="${redis.maxTotal}"></property>
        <property name="maxIdle" value="${redis.maxIdle}" /> 
        <property name="maxWaitMillis" value="${redis.maxWait}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>
    
    
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:host-name="${redis.host}" p:port="${redis.port}" p:pool-config-ref="poolConfig"/>
    
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory"     ref="connectionFactory" />
    </bean>        
    
</beans>
    <!-- 引入項目配置文件 -->
     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
         <property name="locations">
             <list>
                 <value>classpath:redis.properties</value><!-- 引入redis配置文件 -->
                 <value>classpath:jdbc.properties</value><!-- 定義spring-jdbc配置信息路徑 -->
             </list>
         </property>
     </bean>
    
    
    <!-- 自動掃描model,dao和service包(自動注入) -->
    <context:component-scan base-package="com.ffcs.wlan.model,com.ffcs.wlan.dao,com.ffcs.wlan.service" />

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM