基于zookeeper实现配置文件共享

Config.java
public class Config{
    public static final String CONFIG_PATH = "/module1.properties";
    private Map<String,Object> map;
    protected void setMap(Map<String,Object> map){
        this.map = map;
    }
    protected Map<String, Object> getMap() {
        return map;
    }
    public Integer getSampleKey1(){
        return toInteger(map.get("sampleKey1"));
    }
    public String getSampleKey2(){
        return map.get("sampleKey2").toString();
    }
    public Long getSampleKey3(){
        return toLong(map.get("sampleKey3"));
    }
    private Integer toInteger(Object o){
        if(o==null){
            return null;
        }
        return Integer.parseInt(o.toString());
    }
    private Long toLong(Object o){
        if(o==null){
            return null;
        }
        return Long.parseLong(o.toString());
    }

}

Encrypt.java
public class Encrypt {
    private static final String ALGORITHM = "RSA";

    @Test
    public void test() throws Exception{
        /** 为RSA算法创建一个KeyPairGenerator对象 */
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM);
        /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
        //kpg.initialize(512);
        /** 生成密匙对 */
        KeyPair kp = kpg.generateKeyPair();
        /** 得到公钥 */
        Key publicKey = kp.getPublic();
        /** 得到私钥 */
        Key privateKey = kp.getPrivate();
        String pubKey = Base64.getEncoder().encodeToString( SerializationUtils.serialize(publicKey));
        String priKey = Base64.getEncoder().encodeToString( SerializationUtils.serialize(privateKey));
        System.out.println(pubKey);
        System.out.println(priKey);
      /*  Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, (Key)SerializationUtils.deserialize(Base64.getDecoder().decode(pubKey)));
        Map<String,Object> data = new HashMap<>();
        data.put("a", "A");
        String charset = "utf-8";
        byte[] b = cipher.doFinal(JSON.toJSONString(data).getBytes(charset ));
        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, (Key)SerializationUtils.deserialize(Base64.getDecoder().decode(priKey)));
        byte[] res = cipher.doFinal(b);
        System.out.println(JSONObject.parse(res));*/
    }
}

ZkConfig.java
public class ZkConfig {
    @Test
    public void testConfigProvider() {
        ZkClient zkClient = new ZkClient("127.0.0.1:2181", 5000);
        System.out.println("ZK 成功建立连接!");
        Map<String, Object> map = new HashMap<>();
        map.put("sampleKey1", "60");
        map.put("sampleKey2", "this is a test for zk config");
        ZkSerializer zkSerializer = new ZkEncryptedSerializer();
        zkClient.setZkSerializer(zkSerializer);
        zkClient.delete(Config.CONFIG_PATH);
        zkClient.createPersistent(Config.CONFIG_PATH, map);
        zkClient.close();
    }

    @Test
    public void testConfigConsumer() throws IOException {
        ZkClient zkClient = new ZkClient("127.0.0.1:2181", 5000);
        System.out.println("ZK 成功建立连接!");
        Config config = new Config();
        ZkSerializer zkSerializer = new ZkEncryptedSerializer();
        zkClient.setZkSerializer(zkSerializer);
        Object data = zkClient.readData(Config.CONFIG_PATH,true);
        if(data!=null){
            System.out.println(data);
            //config.setMap(JSONObject.parseObject(data.toString(), Map.class));
        }
        System.out.println(config.getMap());
        IZkDataListener listener = new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {
                System.out.println(data);
                /*config.setMap(JSONObject.parseObject(data.toString(), Map.class));
                System.out.println(config.getMap());
                System.out.println(config.getSampleKey1());
                System.out.println(config.getSampleKey2());
                System.out.println(config.getSampleKey3());*/
            }

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
            }
        };
        zkClient.subscribeDataChanges(Config.CONFIG_PATH, listener);
        System.in.read();
        zkClient.close();
    }
}


ZkEncryptedSerializer.java
public class ZkEncryptedSerializer implements ZkSerializer {
    private Charset charset = Charset.forName("utf-8");
    private String publicKey = "rO0ABXNyABRqYXZhLnNlY3VyaXR5LktleVJlcL35T7OImqVDAgAETAAJYWxnb3JpdGhtdAASTGphdmEvbGFuZy9TdHJpbmc7WwAHZW5jb2RlZHQAAltCTAAGZm9ybWF0cQB+AAFMAAR0eXBldAAbTGphdmEvc2VjdXJpdHkvS2V5UmVwJFR5cGU7eHB0AANSU0F1cgACW0Ks8xf4BghU4AIAAHhwAAAAojCBnzANBgkqhkiG9w0BAQE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vdthfGwimCnLS1l195spTRIqYiSLzuxoYEjvWkljc5LclHIYYcc3psFwJAAdHrTjwi0cKTie+pJrPaJu9qFn0jved2HtPdw5plvUqngTqcFQyAFracjk5V8G4QfieIBuHMJU403ZmU6FoMXQJAJhuD2J/AY5K9Ko9VtaiclR9FTmdGpXuCtxNEu2V8PC7ZJw+YLfhCMMjMBmg1PGWe8hXAcuIPm2O9LZANEs9gFwJAOH2KY3V2VZ7OIXL4d+1aSWrWyxZePWPPt15sFX0kGa7Ir9M2qLy9LG16p6hzhlJ7WRTzzW8UR7RjWhwqnOWS6HQABlBLQ1MjOH5yABlqYXZhLnNlY3VyaXR5LktleVJlcCRUeXBlAAAAAAAAAAASAAB4cgAOamF2YS5sYW5nLkVudW0AAAAAAAAAABIAAHhwdAAHUFJJVkFURQ==";
    @Test
    public void test(){
        ZkEncryptedSerializer s = new ZkEncryptedSerializer();
        Map<String, Object> map = new HashMap<>();
        map.put("a", "A");
        map.put("sampleKey1", "60");
        map.put("sampleKey2", "this is a test for zk config");
        byte[] b = s.serialize(map);
        Object o = s.deserialize(b);
        System.out.println(o);
    }
    @Override
    public byte[] serialize(Object data) {
        try {
            byte[] bytes = JSON.toJSONString(data).getBytes(charset);
            Cipher cipher = Cipher.getInstance("RSA");
            Key key = (Key) SerializationUtils.deserialize(Base64.getDecoder().decode(publicKey));
            cipher.init(Cipher.ENCRYPT_MODE, key);
            int start = 0;
            int end = start + 500;
            while (start <= bytes.length) {
                cipher.update(bytes, start, end<bytes.length?end:bytes.length);
                start = end + 1;
                end += 500;
            }
            byte[] res = cipher.doFinal();
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public Object deserialize(byte[] bytes) throws ZkMarshallingError {
        try {
            /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
            Cipher cipher = Cipher.getInstance("RSA");
            Key key = (Key) SerializationUtils.deserialize(Base64.getDecoder().decode(privateKey));
            cipher.init(Cipher.DECRYPT_MODE, key);
            int start = 0;
            int end = start + 500;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while (start <= bytes.length) {
                bos.write(cipher.update(bytes, start, end<bytes.length?end:bytes.length));
                start = end + 1;
                end += 500;
            }
            bos.write(cipher.doFinal());
            String s = new String(bos.toByteArray(), charset);
            return s;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}


ZkJSONSerializer.java
public class ZkJSONSerializer implements ZkSerializer {
    private Charset charset = Charset.forName("utf-8");

    @Override
    public byte[] serialize(Object data) throws ZkMarshallingError {
        return JSON.toJSONString(data).getBytes(charset);
    }

    @Override
    public Object deserialize(byte[] bytes) throws ZkMarshallingError {
        return new String(bytes, charset);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值