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" />
时间: 2024-08-09 14:39:35

redisTemplate 操作的相关文章

Spring中使用RedisTemplate操作Redis(spring-data-redis)

Redis 数据结构简介 Redis可以存储键与5种不同数据结构类型之间的映射,这5种数据结构类型分别为String(字符串).List(列表).Set(集合).Hash(散列)和 Zset(有序集合). 下面来对这5种数据结构类型作简单的介绍: 结构类型 结构存储的值 结构的读写能力 String 可以是字符串.整数或者浮点数 对整个字符串或者字符串的其中一部分执行操作:对象和浮点数执行自增(increment)或者自减(decrement) List 一个链表,链表上的每个节点都包含了一个字

springboot2.1.3 + redisTemplate 操作 redis 3.0.5

近期在整合springboot + redis 的功能,本来想用原生的jedit api,最后想想有点 low,搜了一把,boot已经提供给我们操作的方法,那就是 使用 redisTemplate 或 StringRedisTemplate, 两者是有区别的,可以看下面的说明 1. 两者的关系是StringRedisTemplate继承RedisTemplate. 2. 两者的数据是不共通的:也就是说StringRedisTemplate只能管理StringRedisTemplate里面的数据,

Spring RedisTemplate操作-String操作(2)

@Autowired @Resource(name="redisTemplate") private RedisTemplate<String, String> rt; public void flushdb(){ rt.execute(new RedisCallback<Object>() { public String doInRedis(RedisConnection connection) throws DataAccessException { con

jedis与spring整合及简单的使用RedisTemplate操作

整理一下redis与spring的整合.以及使用redisTemplate.首先是要导入spring所需要的jar.当然还有 jedis-2.1.0.jar,commons-pool-1.5.4.jar,spring-data-redis-1.0.0.RELEASE.jar  (这是我使用的版本,应该不新) 1. 导入完这些jar,开始整理配置文件: 首先就是web.xml.这个还是老样子:贴一下吧 <context-param> <param-name>contextConfig

Spring RedisTemplate操作-xml配置(1)

<context:annotation-config /> <!-- 把非@Controller注解的类转换为bean --> <context:component-scan base-package="tk.tankpao" /> <cache:annotation-driven /> <context:property-placeholder location="classpath:conf/properties/re

Spring RedisTemplate操作-ZSet操作(6)

@Autowired @Resource(name="redisTemplate") private RedisTemplate<String, String> rt; public void flushdb(){ rt.execute(new RedisCallback<Object>() { public String doInRedis(RedisConnection connection) throws DataAccessException { con

Spring RedisTemplate操作-List配置(4)

@Autowired @Resource(name="redisTemplate") private RedisTemplate<String, String> rt; public void flushdb(){ rt.execute(new RedisCallback<Object>() { public String doInRedis(RedisConnection connection) throws DataAccessException { con

Spring RedisTemplate操作-哈希操作(3)

@Autowired @Resource(name="redisTemplate") private RedisTemplate<String, String> rt; public void flushdb(){ rt.execute(new RedisCallback<Object>() { public String doInRedis(RedisConnection connection) throws DataAccessException { con

Spring RedisTemplate操作-Set操作(5)

@Autowired @Resource(name="redisTemplate") private RedisTemplate<String, String> rt; public void flushdb(){ rt.execute(new RedisCallback<Object>() { public String doInRedis(RedisConnection connection) throws DataAccessException { con