JAVA实现读写Codis

  • POM文件pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>

  <groupId>com.laodixiao.connectToCodisgroupId>
  <artifactId>connectToCodisartifactId>
  <version>0.0.1-SNAPSHOTversion>
  <packaging>jarpackaging>

  <name>connectToCodisname>
  <url>http://maven.apache.orgurl>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
  properties>

  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>3.8.1version>
      <scope>testscope>
    dependency>

    <dependency>
  <groupId>redis.clientsgroupId>
  <artifactId>jedisartifactId>
  <version>2.7.2version>
dependency>

<dependency>
  <groupId>com.alibabagroupId>
  <artifactId>fastjsonartifactId>
  <version>1.2.7version>
dependency>


  dependencies>
project>
  • MapSort.java实现Map的排序
package com.laodixiao.connectToCodis.connectToCodis;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class MapSort {

    /**
     * 
     * @param map
     * @return
     */
    public static super V>> Map sortByValue(Map map) {
        List> list = new LinkedList<>(map.entrySet());
        Collections.sort(list, new Comparator>() {
            @Override
            public int compare(Map.Entry o1, Map.Entry o2) {
                return -1*(o1.getValue()).compareTo(o2.getValue());
            }
        });

        Map result = new LinkedHashMap<>();
        for (Map.Entry entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

}
  • 实现Codis的读写
package com.laodixiao.connectToCodis.connectToCodis;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class connectToCodis {

       private static JedisPool pool = null;  

        /** 
         * 构建redis连接池 
         *  
         * @param ip 
         * @param port 
         * @return JedisPool 
         */  
        public static JedisPool getPool() {  
            if (pool == null) {  
                JedisPoolConfig config = new JedisPoolConfig();  
                //最大连接数
                config.setMaxTotal(50);
                //最大空闲连接数
                config.setMaxIdle(10);
                //每次释放连接的最大数目
                config.setNumTestsPerEvictionRun(1024);
                //释放连接的扫描间隔(毫秒)
                config.setTimeBetweenEvictionRunsMillis(30000);
                //连接最小空闲时间
                config.setMinEvictableIdleTimeMillis(1800000);
                //连接空闲多久后释放, 当空闲时间>该值 且 空闲连接>最大空闲连接数 时直接释放
                config.setSoftMinEvictableIdleTimeMillis(10000);
                //获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1
                config.setMaxWaitMillis(1500);
                //在获取连接的时候检查有效性, 默认false
                config.setTestOnBorrow(false);
                //在空闲时检查有效性, 默认false
                config.setTestWhileIdle(true);
                //连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
                config.setBlockWhenExhausted(false);

                //10s超長時間
                pool = new JedisPool(config, "127.0.0.1", 6767, 10000); 

            }  
            return pool;  
        }  

        /** 
         * 返还到连接池 
         *  
         * @param pool  
         * @param redis 
         */  
        public static void returnResource(JedisPool pool, Jedis redis) {  
            if (redis != null) {  
                pool.returnResource(redis);  
            }  
        }  

        /** 
         * codis读取数据
         *  
         * @param key 
         * @return 
         */  
        public static String get(String key){  
            String value = null;  

            JedisPool pool = null;  
            Jedis jedis = null;  
            try {  
                pool = getPool();  
                jedis = pool.getResource();  
                value = jedis.get(key);

            } catch (Exception e) {  
                //释放redis对象  
                pool.returnBrokenResource(jedis);  
                e.printStackTrace();  
            } finally {  
                //返还到连接池  
                returnResource(pool, jedis);  
            } 
            return value;  
        }   

        /**
         * codis写入数据
         * @param key
         * @param value
         */
        public static void set(String key, String value){
            JedisPool pool = null;  
            Jedis jedis = null;  
            try {  
                pool = getPool();  
                jedis = pool.getResource();  
                jedis.set(key, value);

            } catch (Exception e) {  
                //释放redis对象  
                pool.returnBrokenResource(jedis);  
                e.printStackTrace();  
            } finally {  
                //返还到连接池  
                returnResource(pool, jedis);  
            } 
        }

        @SuppressWarnings("unchecked")
        public static void main( String[] args ) throws IOException {
            //读取文件./DouBanData/DouBanData.txt
            String filePath = "./DouBanData/DouBanData.txt";
            File file=new File(filePath);

            //保存结果 cid,//////douBanCidKeys,//////cidSortedKeys
            File fileSave = new File("./result/SimData.txt");
            if(!fileSave.exists()){
                fileSave.createNewFile();
            }
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(fileSave), "utf-8");

            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(new FileInputStream(file),"utf-8");//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;


                int cnt = 0;
                while((lineTxt = bufferedReader.readLine()) != null){
                    //排序后的结果:cid,//////cidSortedKeys
                    StringBuffer cidSortedString = new StringBuffer();
                    String Key = lineTxt.split(",//////")[0];
                    String douBandListString = lineTxt.split(",//////")[2];

                    cnt = cnt + 1;
                    System.out.println(cnt);

                    //組裝key
                    String key = "AlgorithmsCommonBid:ITI:"+ Key;
                    //或取結果
                    String result = get(key);

                    /**
                     * json用法
                     */
                    JSONObject json = JSONObject.parseObject(result);
                    if(json!=null){

                        cidSortedString.append(Key+",//////");
                        cidSortedString.append(douBandListString+",//////");

                        String rst = json.get("Results").toString().replace('{', ' ').replace('}', ' ').trim();
                        String[] rstArray = rst.split(",");
                        Map map = new HashMap();
                        for (int i=0; i":")[0].replace('"', ' ').trim(), Double.parseDouble(rstArray[i].split(":")[1]));
                        }
                        //map按value降序排列
                        Map mapSorted = MapSort.sortByValue(map);
                        StringBuffer cidSortedStringTmp = new StringBuffer();
                        for (Object key1 : mapSorted.keySet()) {  
                            cidSortedStringTmp.append(key1+"/");
                        }
                        if (cidSortedStringTmp.length()<=0) {
                            cidSortedStringTmp.append("/");
                        }
                        String strTmpString = cidSortedStringTmp.substring(0,cidSortedStringTmp.length()-1);

                        cidSortedString.append(strTmpString+"\r\n");
                        System.out.println(cidSortedString);
                        osw.write(cidSortedString.toString());
                    }
                }
                read.close();
            }

          //关闭文件输出流
            osw.flush();
            osw.close();
        }
}

“`

你可能感兴趣的:(JAVA,java,codis,redis)