zoukankan      html  css  js  c++  java
  • spring data redis jackson 配置,工具类

    spring data redis 序列化有jdk 、jackson、string 等几种类型,自带的jackson不熟悉怎么使用,于是用string类型序列化,把对象先用工具类转成string,代码如下:

    application.xml中配置

    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
            <property name="hostName" value="${redis.hostName}"></property>
            <property name="port" value="${redis.port}"></property>
            <property name="password" value="${redis.password}"></property>
            <property name="timeout" value="${redis.timeout}" />  
            <property name="usePool" value="true" />  
            <property name="poolConfig" ref="jedisPoolConfig" /> 
        </bean>
        
        <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
            <property name="maxTotal" value="${redis.maxTotal}"></property>  
            <property name="maxIdle" value="${redis.maxIdle}"></property>  
            <property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property>
            <property name="testOnBorrow" value="${redis.testOnBorrow}"></property>  
        </bean>
        
        <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        
        <!-- <bean id="jacksonJsonRedisSerializer" class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer" >
            <constructor-arg type="java.lang.Class" value="java.lang.Object"/>
        </bean> -->
        
        <bean id="jacksonJsonRedisSerializer" class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer" >
            <constructor-arg type="java.lang.Class" value="java.lang.Object"/>
        </bean>
        
        
        <bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
              
        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
            <property name="connectionFactory" ref="jedisConnectionFactory"></property>
            <property name="keySerializer" ref="stringRedisSerializer"/>  
            <property name="valueSerializer" ref="stringRedisSerializer" />  
            <property name="hashKeySerializer" ref="stringRedisSerializer" />  
            <property name="hashValueSerializer" ref="stringRedisSerializer"/>  
        </bean>
    <bean id="propertyConfigurer"
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <list>
                    <value>classpath:jdbc.properties</value>
                    <value>classpath:redis.properties</value>
                </list>
            </property>
        </bean>
    
    
    redis.properties
    
    #redis连接池配置
    redis.maxTotal=300
    redis.maxIdle=20
    #读取超时
    redis.maxWaitMillis=5000
    redis.testOnBorrow=true
    
    #redis连接配置
    redis.hostName=192.168.100.75
    redis.port=6379
    redis.password=desc@1997
    #连接超时
    redis.timeout=5000

    RedisBaseDao

    @Component
    public class RedisBaseDao {
        /**
         * 日志记录
         */
        private static Logger logger = Logger.getLogger(RedisBaseDao.class);
        @Autowired
        protected RedisTemplate<String, String> redisTemplate;
        
    
        public RedisTemplate<String, String> getRedisTemplate() {
            return redisTemplate;
        }
        /**
         * 缓存value操作
         * @param k
         * @param v
         * @param time
         * @return
         */
        public boolean cache(String k, Object v, long time) {
            String key = k;
            try {
                long s=System.currentTimeMillis();
                ValueOperations<String, String> valueOps =  redisTemplate.opsForValue();
                valueOps.set(key, Json2Util.obj2String(v));
                if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
                long e=System.currentTimeMillis();
                if(e-s>2000){
                    logger.error("key:"+key+" redis time use"+(e-s));
                } else if(logger.isDebugEnabled()){
                    logger.debug("key:"+key+" redis time use"+(e-s));
                }
                return true;
            } catch (Throwable t) {
                logger.error("缓存[" + key + "]失败, value[" + v + "]", t);
            }
            return false;
        }
        /**
         * 添加list
         * @Autor : xiongjinpeng  jpx_011@163.com
         * @Date  : 2017年7月7日 下午2:37:31 
         * @param k
         * @param v
         * @param time
         * @return
         */
    //    public boolean cacheList(String k, Collection v, long time) {
    //        String key = k;
    //        try {
    //            long s=System.currentTimeMillis();
    //            redisTemplate.delete(key);
    //            ListOperations<String, Object> list=redisTemplate.opsForList();
    //            list.leftPushAll(key, v);
    //            if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
    //            long e=System.currentTimeMillis();
    //            if(e-s>2000){
    //                logger.error("redis time use "+(e-s));
    //            }
    //            return true;
    //        } catch (Throwable t) {
    //            logger.error("缓存[" + key + "]失败, value[" + v + "]", t);
    //        }
    //        return false;
    //    }
    //    public boolean cacheList(String k, Collection v) {
    //        return cacheList(k, v, -1);
    //    }
    //    public <T> List<T> getList(String k,int start,int end) {
    //        try {
    //            long s=System.currentTimeMillis();
    //            ListOperations<String, Object> valueOps=redisTemplate.opsForList();
    //            List<T> o=(List<T>) valueOps.range(k, start, end);
    //            long e=System.currentTimeMillis();
    //            if(e-s>2000){
    //                logger.error("redis time use "+(e-s));
    //            }
    //            return o;
    //        } catch (Throwable t) {
    //            logger.error("获取缓存失败key[" + k + ", error[" + t + "]");
    //        }
    //        return null;
    //    }
    //    public <T> List<T> getList(String k){
    //        return getList(k, 0, -1);
    //    }
        /**
         * 缓存value操作
         * @param k
         * @param v
         * @return
         */
        public boolean cache(String k, Object v) {
            return cache(k, v, RedisUtil.keytimeout);
        }
    
        public boolean containsKey(String key) {
            try {
                return redisTemplate.hasKey(key);
            } catch (Throwable t) {
                logger.error("判断缓存存在失败key[" + key + ", error[" + t + "]");
            }
            return false;
        }
    
        /**
         * 获取缓存
         * @param k
         * @return
         */
    //    public Object get(String k) {
    //        return get(k,RedisUtil.keytimeout);
    //    }
    //    
    //    public Object get(String k,long time) {
    //        try {
    //            long s=System.currentTimeMillis();
    //            ValueOperations<String, String> valueOps =  redisTemplate.opsForValue();
    //            Object o=valueOps.get(k);
    //            if (time > 0) redisTemplate.expire(k, time, TimeUnit.SECONDS);
    //            long e=System.currentTimeMillis();
    //            if(e-s>2000){
    //                logger.error("key:"+k+" redis time use "+(e-s));
    //            } else if(logger.isDebugEnabled()){
    //                logger.debug("key:"+k+" redis time use"+(e-s));
    //            }
    //            return o;
    //        } catch (Throwable t) {
    //            logger.error("获取缓存失败key[" + k + ", error[" + t + "]");
    //        }
    //        return null;
    //    }
        
        
        public <T> T get(String k,Class<T> clazz) {
            return get(k,RedisUtil.keytimeout, clazz);
        }
        public <T> T get(String k,long time,Class<T> clazz) {
            try {
                long s=System.currentTimeMillis();
                ValueOperations<String, String> valueOps =  redisTemplate.opsForValue();
                String o=valueOps.get(k);
                if (time > 0) redisTemplate.expire(k, time, TimeUnit.SECONDS);
                long e=System.currentTimeMillis();
                if(e-s>2000){
                    logger.error("key:"+k+" redis time use "+(e-s));
                } else if(logger.isDebugEnabled()){
                    logger.debug("key:"+k+" redis time use"+(e-s));
                }
                if(o!=null){
                    return Json2Util.getObjectMapper().readValue(o, clazz);
                }
            } catch (Throwable t) {
                logger.error("获取缓存失败key[" + k + ", error[" + t + "]");
            }
            return null;
        }
        public <T> List<T> getList(String k,long time,Class<T> clazz) {
            try {
                long s=System.currentTimeMillis();
                ValueOperations<String, String> valueOps =  redisTemplate.opsForValue();
                String o=valueOps.get(k);
                if (time > 0) redisTemplate.expire(k, time, TimeUnit.SECONDS);
                long e=System.currentTimeMillis();
                if(e-s>2000){
                    logger.error("key:"+k+" redis time use "+(e-s));
                } else if(logger.isDebugEnabled()){
                    logger.debug("key:"+k+" redis time use"+(e-s));
                }
                if(o!=null){
                    JavaType javaType = Json2Util.getObjectMapper().getTypeFactory().constructParametricType(List.class, clazz);  
                    List<T> list = Json2Util.getObjectMapper().readValue(o, javaType);  
                    return list;
                }
            } catch (Throwable t) {
                logger.error("获取缓存失败key[" + k + ", error[" + t + "]");
            }
            return null;
        }
        public <T> List<T> getList(String k,Class<T> clazz) {
            return getList(k, RedisUtil.keytimeout, clazz);
        }
        /**
         * 移除缓存
         * @param key
         * @return
         */
        public boolean remove(String key) {
            try {
                redisTemplate.delete(key);
                return true;
            } catch (Throwable t) {
                logger.error("获取缓存失败key[" + key + ", error[" + t + "]");
            }
            return false;
        }
        /**
         * 模糊匹配,不建议使用,影响性能,只在一些数据重置的时候使用
         * @Date  : 2017年7月6日 下午4:13:45 
         * @param pattern
         * @return
         */
        @Deprecated
        public Set<String> keys(String pattern) {
            try {
                long s=System.currentTimeMillis();
                Set<String> keys=redisTemplate.keys(pattern);
                long e=System.currentTimeMillis();
                if(e-s>2000){
                    logger.error("redis time use "+(e-s));
                }
                return keys;
            } catch (Throwable t) {
                logger.error("获取缓存失败pattern[" + pattern + ", error[" + t + "]");
            }
            return null;
        }
        
        public String flushDB() {
            return redisTemplate.execute(new RedisCallback<String>() {
                public String doInRedis(RedisConnection connection) throws DataAccessException {
                    connection.flushDb();
                    return "ok";
                }
            });
        }
        
        public long dbSize() {
            return redisTemplate.execute(new RedisCallback<Long>() {
                public Long doInRedis(RedisConnection connection) throws DataAccessException {
                    return connection.dbSize();
                }
            });
        }
    }

    RedisUtil

    public class RedisUtil {
        //单例
        private RedisUtil(){}
        private static RedisBaseDao dao=null;
        static {
            if(dao==null){
                synchronized (RedisUtil.class) {
                    if(dao==null){
                        dao=ContextUtil.getBean(RedisBaseDao.class);
                        try {
                            String keytimeoutstr=ContextUtil.getInitConfig("redis.keytimeout");
                            String unit=keytimeoutstr.substring(keytimeoutstr.length()-1);
                            Integer num=Integer.parseInt(keytimeoutstr.substring(0,keytimeoutstr.length()-1));
                            if(unit.equals("d")){
                                keytimeout=num*24*60*60;
                            } else if(unit.equals("h")){
                                keytimeout=num*60*60;
                            } else if(unit.equals("m")){
                                keytimeout=num*60;
                            } else if(unit.equals("s")){
                                keytimeout=num;
                            } else {
                                throw new RuntimeException("redis key timeout初始化失败");
                            }
                        } catch (Exception e) {
                            throw new RuntimeException("redis key timeout初始化失败");
                        }
                    }
                }
            }
        }
        public static RedisBaseDao getRedisDao() {
            return dao;
        }
        
        public static long keytimeout=30*24*60*60;//
        
    }

    使用类,

    CommonCache

    public class CommonCache {
        
        /**
         * 查询缓存
    
         * @Date  : 2017年7月5日 下午3:15:47 
         * @param userId
         * @return
         */
        public static FileCache queryFileCache(Long fid){
            if(fid==null){
                return null;
            }
            String key=CachePrefix.filecache_prefix+fid;
            FileCache u=RedisUtil.getRedisDao().get(key,FileCache.class);
            if(u==null){
                return refreshFileCache(fid);
            } else {
                return u;
            }
        }
        /**
         * 刷新缓存
    
         * @Date  : 2017年7月5日 下午3:15:39 
         * @param userId
         */
        public static FileCache refreshFileCache(Long fid){
            if(fid==null){
                return null;
            }                                           
            IBaseDao dao=ContextUtil.getBean(IBaseDao.class);
            String key=CachePrefix.filecache_prefix+fid;
            StringBuffer sql = new StringBuffer();
            sql.append("select f.f_isdeleted,f.f_id,f.f_name,f.f_extension,f.f_type,f.f_size,f.f_create_time,f.f_oss_bucket from t_file f where f.f_id=?");
            FileCache userExt = dao.queryObjectBySql(FileCache.class, sql.toString(), new Object[]{fid});
            RedisUtil.getRedisDao().cache(key, userExt);
            return userExt;
        }
        
    }

     json使用jackson个人感觉是最快的

    Json2Util

    import com.fasterxml.jackson.annotation.JsonInclude.Include;
    import com.fasterxml.jackson.core.JsonParser.Feature;
    import com.fasterxml.jackson.databind.DeserializationFeature;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    
    /**
     * @Description : 
     * @Autor : xiongjinpeng  jpx_011@163.com
     * @Date  : 2016年1月26日 上午10:11:41 
     * @version : 
     */
    public class Json2Util {
    
        private static ObjectMapper objectMapper=null;
        static {
            if(objectMapper==null){
                synchronized (Json2Util.class) {
                    if(objectMapper==null){
                        objectMapper=new ObjectMapper();
                        objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
                        objectMapper.setSerializationInclusion(Include.NON_NULL);
                        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
                    }
                }
            }
        }
        public static ObjectMapper getObjectMapper() {
            return objectMapper;
        }
        public static String obj2String(Object obj){
            String s = "";
            try {
                s = getObjectMapper().writeValueAsString(obj);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return s;
        }
        private Json2Util(){}
        
        public static void main(String[] args) throws Exception{
        }
    }
  • 相关阅读:
    linux shell 中"2>&1"含义-完美理解-费元星
    浅谈移动端设备标识码:DeviceID、IMEI、IDFA、UDID和UUID -费元星
    费元星-关于百度在数据仓库-层级架构上的思考
    费元星的第二代车,基于图像识别和超声波的无人智能小车
    【完美解决】Spark-SQL、Hive多 Metastore、多后端、多库
    【费元星】crt 无法上传文件,总是显示盾牌表示-完美解决
    【费元星原创】一键安装Hadoo2.7.6 集群完全分布式脚本-完美解决
    【研发工具必备】费元星的技术成长流线图-第一版
    【shell mysql 导出数据到csv脚本,完美解决乱码转义符等问题】-费元星
    【Linux搭建创建FTP服务器】---完美解决
  • 原文地址:https://www.cnblogs.com/xiongjinpeng/p/7168734.html
Copyright © 2011-2022 走看看