jedis存储对象

jedis存储对象,实际就是存字节,spring.data.redis我没找到可以存的,于是用了jedis,里面有挑战的技术点很多。

测试代码:

package net.highersoft.jedis;

import java.util.Calendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.highersoft.entity.Result;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Protocol;

public class TestJedisObj {
	private  static Logger log=LoggerFactory.getLogger(TestJedisObj.class);
	
	public static void main2(String args[]) throws Exception{
		redis.clients.jedis.JedisCluster jc;
		Jedis j =  new Jedis("192.168.0.xx", 6379, false);
        j.connect();
        j.set("1".getBytes(), SerializeUtil.serialize(new Result()));
        j.set("2".getBytes(), SerializeUtil.serialize(new Result()));
        String lua="return redis.call('get','1')";
        String script=lua+"";
        Object obj=j.eval(script.getBytes());
        
        

        byte tmp[]=SerializeUtil.serialize(new Result());
        System.out.println(SerializeUtil.unserialize(SerializeUtil.serialize(new Result())));       
        System.out.println(SerializeUtil.unserialize((byte[])obj));
        
        lua="return redis.call('mget','1','2')";
        obj=j.eval(lua.getBytes());
        List<byte[]> rstList=(List<byte[]>)obj;
        System.out.println(rstList.size());
        System.out.println(SerializeUtil.unserialize(rstList.get(0)));
        
	}
	public static void main(String args[]) throws Exception{
		redis.clients.jedis.JedisCluster jc;
		MgetBinaryJedis j =  new MgetBinaryJedis("192.168.0.xx", 6379);
        j.connect();

        
        int keyLen=3000;
		/*
    	for(int i=0;i<keyLen;i++) {
    		log.info("set "+i);
    		Result rs=new Result();
    		rs.setAipicscore((float)(i*1.0));
    		rs.setCatalogs(new String[] {String.valueOf(i)});
    		rs.setColdStatus(String.valueOf(i));
    		rs.setFilterLowConvert(String.valueOf(i));
    		rs.setGradingVal(String.valueOf(i));
    		rs.setGreenScreenFlag(String.valueOf(i));
    		rs.setIsGreen((byte)(i%2));
    		rs.setRectype(String.valueOf(i));
    		rs.setScore((float)(i*1.0));
    		rs.setSimitemcode(String.valueOf(i));
    		rs.setSimscore((float)(i*1.0));
    		rs.setSrcitemcode(String.valueOf(i));
    		
    		try {
    			j.set(String.valueOf(i).getBytes(), SerializeUtil.serialize(rs), "NX".getBytes(),"EX".getBytes(),3600l);
    		}catch(Exception e) {
    			log.error(e.getMessage());
    		}
    	}
    	*/
    	
    	
		
		
		for(int i=0;i<10;i++) {
			
			StringBuffer sb=new StringBuffer();
			byte[][] allLua=new byte[keyLen][];
			for(int k=0;k<keyLen;k++) {
				
				//sb.append(",'"+String.valueOf(k)+"'");
				sb.append(String.valueOf(k)+" ");
				allLua[k]=String.valueOf(k).getBytes();
			}
			
			//mget命令受lua语言限制,参数传不了几个,能传248个左右
			//String lua="return redis.call('mget'"+sb.toString()+")";
			String lua="local result ={} \n"
					+ "for i = 1,#(KEYS) do \n"
					+ "   result[i]= redis.call('get',KEYS[i]) \n"
					+ "end \n"
					+ "return result";
			//System.out.println(lua);
			Calendar start=Calendar.getInstance();
			//https://redis.io/commands/eval
	        //Object obj=j.eval(lua.getBytes(),Protocol.toByteArray(2),new byte[][] {"1".getBytes(),"2".getBytes()});
	        
			Object obj=j.eval(lua.getBytes(),keyLen,allLua);
	        List<byte[]> rstList=(List<byte[]>)obj;
			
			log.info("total:{}ms,key length:{}, value length:{}",new String[] {String.valueOf(Calendar.getInstance().getTimeInMillis()-start.getTimeInMillis()),String.valueOf(keyLen),String.valueOf(rstList.size())});
			Thread.sleep(1000);
		}
		
    	
    	log.info("end");
        
        
        
       
        
        
	}
	

}
工具类:

package net.highersoft.jedis;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {
	public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
         ByteArrayOutputStream baos = null;
         try {
              // 序列化
             baos = new ByteArrayOutputStream();
             oos = new ObjectOutputStream(baos);
             oos.writeObject(object);
              byte[] bytes = baos.toByteArray();
              return bytes;
        } catch (Exception e) {

        }
         return null;
  }
	
   public static Object unserialize( byte[] bytes) {
        ByteArrayInputStream bais = null;
         try {
              // 反序列化
             bais = new ByteArrayInputStream(bytes);
             ObjectInputStream ois = new ObjectInputStream(bais);
              return ois.readObject();
        } catch (Exception e) {

        }
         return null;
  }
   public static Object unserialize( Byte[] bytes) {
	   byte[] bs=new byte[bytes.length];
	   for(int i=0;i<bytes.length;i++) {
		   bs[i]=bytes[i];
	   }
       ByteArrayInputStream bais = null;
        try {
             // 反序列化
            bais = new ByteArrayInputStream(bs);
            ObjectInputStream ois = new ObjectInputStream(bais);
             return ois.readObject();
       } catch (Exception e) {

       }
        return null;
 }
}
还要继承一下Jedis,才能做解决可变参数的动态化问题。

package net.highersoft.jedis;

import redis.clients.jedis.Jedis;

public class MgetBinaryJedis extends Jedis {
	
	public MgetBinaryJedis(final String host, final int port) {
	    super(host, port);
	  }
	public Object eval(byte[] script, byte[] keyCount, byte[][] params) {
	    client.setTimeoutInfinite();
	    try {
	      client.eval(script, keyCount, params);
	      return client.getOne();
	    } finally {
	      client.rollbackTimeout();
	    }
	    
	    
	  }

	  

}
相关的实体类:

package net.highersoft.entity;

import java.io.Serializable;


public class Result implements Serializable {
    private String srcitemcode;
    private String simitemcode;
    private float simscore;
    private String gradingVal;
    private Byte isGreen;
    private String[] catalogs;
    private float score;
    private float aipicscore;
    private String rectype;
    private String greenScreenFlag;
    private String filterLowConvert;
    private String coldStatus;
	public String getSrcitemcode() {
		return srcitemcode;
	}
	public void setSrcitemcode(String srcitemcode) {
		this.srcitemcode = srcitemcode;
	}
	public String getSimitemcode() {
		return simitemcode;
	}
	public void setSimitemcode(String simitemcode) {
		this.simitemcode = simitemcode;
	}
	public float getSimscore() {
		return simscore;
	}
	public void setSimscore(float simscore) {
		this.simscore = simscore;
	}
	public String getGradingVal() {
		return gradingVal;
	}
	public void setGradingVal(String gradingVal) {
		this.gradingVal = gradingVal;
	}
	public Byte getIsGreen() {
		return isGreen;
	}
	public void setIsGreen(Byte isGreen) {
		this.isGreen = isGreen;
	}
	public String[] getCatalogs() {
		return catalogs;
	}
	public void setCatalogs(String[] catalogs) {
		this.catalogs = catalogs;
	}
	public float getScore() {
		return score;
	}
	public void setScore(float score) {
		this.score = score;
	}
	public float getAipicscore() {
		return aipicscore;
	}
	public void setAipicscore(float aipicscore) {
		this.aipicscore = aipicscore;
	}
	public String getRectype() {
		return rectype;
	}
	public void setRectype(String rectype) {
		this.rectype = rectype;
	}
	public String getGreenScreenFlag() {
		return greenScreenFlag;
	}
	public void setGreenScreenFlag(String greenScreenFlag) {
		this.greenScreenFlag = greenScreenFlag;
	}
	public String getFilterLowConvert() {
		return filterLowConvert;
	}
	public void setFilterLowConvert(String filterLowConvert) {
		this.filterLowConvert = filterLowConvert;
	}
	public String getColdStatus() {
		return coldStatus;
	}
	public void setColdStatus(String coldStatus) {
		this.coldStatus = coldStatus;
	}

    
}

文/程忠 浏览次数:0次   2021-10-17 06:19:10

相关阅读


评论: