1.通过util.zip带的gzip压缩程序 

Coherence对象压缩程序如下

package coherencetest;

import com.tangosol.net.CacheFactory;

import java.util.zip.*;
import java.io.*;
import com.tangosol.net.CacheFactory;
import com.tangosol.net.ConfigurableCacheFactory;
import com.tangosol.net.DefaultConfigurableCacheFactory;
import com.tangosol.net.NamedCache;

public class CompressObject {
public CompressObject() {
super();
}

public static byte[] writeCompressObject(Person object)
{
byte[] data_=null;
try
{
//建立字节数组输出流
ByteArrayOutputStream o = new ByteArrayOutputStream();
//建立gzip压缩输出流
GZIPOutputStream gzout=new GZIPOutputStream(o);
//建立对象序列化输出流
ObjectOutputStream out = new ObjectOutputStream(gzout);
out.writeObject(object);
out.flush();
out.close();
gzout.close();
//返回压缩字节流
data_=o.toByteArray();
o.close();
}catch(IOException e)
{
System.out.println(e);
}
return(data_);
}

public static Person readCompressObject(byte[] data_)
{
Person object_=null;
try
{
//建立字节数组输入流
ByteArrayInputStream i = new ByteArrayInputStream(data_);
//建立gzip解压输入流
GZIPInputStream gzin=new GZIPInputStream(i);
//建立对象序列化输入流
ObjectInputStream in = new ObjectInputStream(gzin);
//按制定类型还原对象
object_=(Person)in.readObject();
i.close();
gzin.close();
in.close();
}catch(ClassNotFoundException e)
{
System.out.println(e);
}catch(IOException e)
{
System.out.println(e);
}

return(object_);
}

public static void main (String [] args) {
CompressObject co = new CompressObject();

Person person = new Person();

writeObjectToFile("zipcompress_before",person);

//System.out.println(person);
byte[] compressperson = writeCompressObject(person);

writeBytesToFile("zipcompress_after",compressperson);

String personstr = new String(compressperson);

NamedCache cache = CacheFactory.getCache("POFSample");
for (int i=0;i<10000;i++) {
// cache.put (i,compressperson);
cache.put (Integer.toString(i),compressperson);

}
System.out.println("put success");

byte[] a = (byte[]) cache.get("1");
Person person1 = readCompressObject(a);
System.out.println(person1.getFirstname());
System.out.println(person1.getLastname());
System.out.println(person1.getAddress());

//cache.retrieveCache();
}

public static void writeObjectToFile(String Filename, Object obj) {

try {

FileOutputStream outStream = new FileOutputStream("c:/"+Filename);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outStream);
objectOutputStream.writeObject(obj);
outStream.close();
System.out.println("successful");

// if file doesnt exists, then create it
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void writeBytesToFile(String Filename, byte[] objs) {

try {

FileOutputStream outStream = new FileOutputStream("c:/"+Filename);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outStream);
objectOutputStream.write(objs);
outStream.close();
System.out.println("successful");

// if file doesnt exists, then create it
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}

测试了一下,原来的对象3.96kb,然后经过压缩以后2.01K,还是有减少。

但通过Coherence的visualvm看了一下,发现平均对象大小是1byte.难道coherence只存放对象的指针吗?

2.通过kryo的序列化方法

package coherencetest;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import com.tangosol.dev.assembler.New;
import com.tangosol.net.CacheFactory;
import com.tangosol.net.NamedCache;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.objenesis.strategy.SerializingInstantiatorStrategy;
import org.objenesis.strategy.StdInstantiatorStrategy;

import java.io.IOException;
import java.io.ObjectOutputStream;

public class kryoCompress {
static int BYTES_LENTH = 20000;

public kryoCompress() {
super();
}

public static void main(String[] args) {
// TODO Auto-generated method stub

Person person = new Person();

writeObjectToFile("person2",person);

Kryo kryo = new Kryo();
kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());

byte[] scbytes = null;
try {
scbytes= kryocompress(person,kryo);
//System.out.println(ObjectSizeFetcher.getObjectSize(scbytes));
writeBytesToFile("personcompress",scbytes);
} catch (Exception e) {
System.out.println("kryocompress:"+e.getMessage());
}

Person backsc =kryodeserialize(scbytes,kryo);
System.out.println("kryodeserialize:["+backsc.getAddress()+"]");

}

public static byte[] kryocompress(Person object, Kryo kryo) throws IOException {

byte[] buffer = new byte[BYTES_LENTH];

Output out = new Output(buffer);

kryo.writeObject(out, object);

//System.out.println("kryocompress====total:"+out.total());
//System.out.println("kryocompress====position:"+out.position());

return out.toBytes();

}

public static Person kryodeserialize(byte[] bytes,Kryo kryo) {
Input input = null;

try {

input = new Input(bytes);

return (Person)kryo.readObject(input, Person.class);
} catch (Exception e) {
System.out.println("kryodeserialize==#==["+e.getMessage()+"]");
//System.out.println(e.getMessage());
}
return null;

}

public static void writeObjectToFile(String Filename, Object obj) {

try {

FileOutputStream outStream = new FileOutputStream("c:/"+Filename);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outStream);
objectOutputStream.writeObject(obj);
outStream.close();
System.out.println("successful");

// if file doesnt exists, then create it
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void writeBytesToFile(String Filename, byte[] objs) {

try {

FileOutputStream outStream = new FileOutputStream("c:/"+Filename);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outStream);
objectOutputStream.write(objs);
outStream.close();
System.out.println("successful");

// if file doesnt exists, then create it
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}

测试了一下,原来标准的3.96K的对象,经过kryo序列化后变成了3.01K.可见应该只是序列化上的优化,压缩率比较小.

计算Coherence对象大小的程序

另外附上一个计算coherence对象大小的程序

package coherencetest;

import java.text.DecimalFormat;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;

import com.tangosol.net.CacheFactory;

import java.io.IOException;

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class CalculateTheSizeOfPeopleCache {

@SuppressWarnings({ "unchecked", "rawtypes" })
private void run() throws Exception {

// Enable JMX support in this Coherence data grid session...
System.setProperty("tangosol.coherence.management", "all");

// Create a sample cache just to access the data grid...
CacheFactory.getCache(MBeanServerFactory.class.getName());

// Gets the JMX server from Coherence data grid...
MBeanServer jmxServer = getJMXServer();
System.out.println(jmxServer.toString());
if (jmxServer != null)
System.out.println("can not get jmxServer");

//MBeanServerConnection jmxServer = getJMXServer();

// Creates a internal data structure that would maintain
// the statistics from each cache in the data grid...
Map cacheList = new TreeMap();
Set jmxObjectList = jmxServer.queryNames(new ObjectName("Coherence:type=Cache,*"), null);
if (jmxObjectList !=null) {
System.out.println("can not get jmxOBjectList");
System.out.println(jmxObjectList.size());
}
for (Object jmxObject : jmxObjectList) {
System.out.println("Enter");
ObjectName jmxObjectName = (ObjectName) jmxObject;
String cacheName = jmxObjectName.getKeyProperty("name");
if (cacheName.equals(MBeanServerFactory.class.getName())) {
continue;
} else {
cacheList.put(cacheName, new Statistics(cacheName));
}
}

// Updates the internal data structure with statistic data
// retrieved from caches inside the in-memory data grid...
Set<String> cacheNames = cacheList.keySet();
for (String cacheName : cacheNames) {
Set resultSet = jmxServer.queryNames(
new ObjectName("Coherence:type=Cache,name=" + cacheName + ",*"), null);
for (Object resultSetRef : resultSet) {
ObjectName objectName = (ObjectName) resultSetRef;
if (objectName.getKeyProperty("tier").equals("back")) {
int unit = (Integer) jmxServer.getAttribute(objectName, "Units");
int size = (Integer) jmxServer.getAttribute(objectName, "Size");
Statistics statistics = (Statistics) cacheList.get(cacheName);
statistics.incrementUnit(unit);
statistics.incrementSize(size);
cacheList.put(cacheName, statistics);
}
}
}

// Finally... print the objects from the internal data
// structure that represents the statistics from caches...
cacheNames = cacheList.keySet();
for (String cacheName : cacheNames) {
Statistics estatisticas = (Statistics) cacheList.get(cacheName);
System.out.println(estatisticas);
}

}
/*
public static MBeanServerConnection getJMXServer() throws IOException {
JMXServiceURL url = new JMXServiceURL("service://...");
JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
return jmxc.getMBeanServerConnection();
}
*/
public MBeanServer getJMXServer() {
MBeanServer jmxServer = null;
for (Object jmxServerRef : MBeanServerFactory.findMBeanServer(null)) {
jmxServer = (MBeanServer) jmxServerRef;
System.out.println(jmxServer.getDefaultDomain().toString());
if (jmxServer.getDefaultDomain().equals(DEFAULT_DOMAIN) || DEFAULT_DOMAIN.length() == 0) {
break;
}
jmxServer = null;
}
if (jmxServer == null) {
jmxServer = MBeanServerFactory.createMBeanServer(DEFAULT_DOMAIN);
}
return jmxServer;
}

private class Statistics {

private long unit;
private long size;
private String cacheName;

public Statistics(String cacheName) {
this.cacheName = cacheName;
}

public void incrementUnit(long unit) {
this.unit += unit;
}

public void incrementSize(long size) {
this.size += size;
}

public long getUnit() {
return unit;
}

public long getSize() {
return size;
}

public double getUnitInMB() {
return unit / (1024.0 * 1024.0);
}

public double getAverageSize() {
return size == 0 ? 0 : unit / size;
}

public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("\nCache Statistics of '").append(cacheName).append("':\n");
sb.append(" - Total Entries of Cache -----> " + getSize()).append("\n");
sb.append(" - Used Memory (Bytes) --------> " + getUnit()).append("\n");
sb.append(" - Used Memory (MB) -----------> " + FORMAT.format(getUnitInMB())).append("\n");
sb.append(" - Object Average Size --------> " + FORMAT.format(getAverageSize())).append("\n");
return sb.toString();
}

}

public static void main(String[] args) throws Exception {
new CalculateTheSizeOfPeopleCache().run();
}

public static final DecimalFormat FORMAT = new DecimalFormat("###.###");
public static final String DEFAULT_DOMAIN = "DefaultDomain";
public static final String DOMAIN_NAME = "Coherence";
//public static final String DOMAIN_NAME = "enie's cluster";

}

需要的条件是:

  • 不能以Coherence Extend Client的方式连入集群
  • 需要开启-Dtangosol.coherence.management.remote=true  -Dtangosol.coherence.management=all 参数
  • 需要和cluster环境保持一直,生产就是生产,开发就是开发,-Dtangosol.coherence.mode=prod

输出如下:

Cache Statistics of 'POFSample':
- Total Entries of Cache -----> 10001
- Used Memory (Bytes) --------> 10001
- Used Memory (MB) -----------> 0.01
- Object Average Size --------> 1

Coherence对象压缩以及对象大小计算的更多相关文章

  1. Java对象的内存布局以及对象所需内存大小计算详解

    1. 内存布局 在HotSpot虚拟机中,对象的内存布局可以分为三部分:对象头(Header). 实例数据(Instance Data)和对齐填充(Padding). 1) 对象头(Header): ...

  2. Java对象大小计算

    这篇说说如何计算Java对象大小的方法.之前在聊聊高并发(四)Java对象的表示模型和运行时内存表示 这篇中已经说了Java对象的内存表示模型是Oop-Klass模型. 普通对象的结构如下,按64位机 ...

  3. JVM —— Java 对象占用空间大小计算

    零. 为什么要知道 Java 对象占用空间大小 缓存的实现: 在设计 JVM 内缓存时(不是借助 Memcached. Redis 等), 须要知道缓存的对象是否会超过 JVM 最大堆限制, 假设会超 ...

  4. java对象在内存的大小

    前言 一直以来,对java对象大小的概念停留在基础数据类型,比如byte占1字节,int占4字节,long占8字节等,但是一个对象包含的内存空间肯定不只有这些. 假设有类A和B,当new A()或者n ...

  5. 获取JAVA对象占用的内存大小

    介绍两种获取JAVA对象内存大小的方法. 第一种:Instrumentation 简介: 使用java.lang.instrument 的Instrumentation来获取一个对象的内存大小.利用I ...

  6. [翻译] 编写高性能 .NET 代码--第二章 GC -- 减少大对象堆的碎片,在某些情况下强制执行完整GC,按需压缩大对象堆,在GC前收到消息通知,使用弱引用缓存对象

    减少大对象堆的碎片 如果不能完全避免大对象堆的分配,则要尽量避免碎片化. 对于LOH不小心就会有无限增长,但LOH使用的空闲列表机制可以减轻增长的影响.利用这个空闲列表,我们可以在两块分配区域中间找到 ...

  7. 如何获取一个Java对象所占内存大小

    新建一个maven工程 我们先在IDEA中新建一个名为ObjectSizeFetcherAgent的maven工程,如下图: 在maven项目中的pom.xml中新增一个打jar包的插件,如下: &l ...

  8. 4种方法教你如何查看java对象所占内存大小

    摘要:本文讲述4种查看java对象所占内存大小的方法 本文分享自华为云社区<查看java对象所占内存大小>,作者:xiewenci. 计算java对象所占内存大小 1.使用jdk8自带AP ...

  9. js压缩xml字符串,将xml字符串转换为xml对象,将xml对象转换为json对象

    /** * 压缩xml字符串 */ function compressXmlStr(str){ var prefix, suffix; var i = str.indexOf("\r&quo ...

随机推荐

  1. mongodb安全

    1.流程: (1)创建超级管理员 (2)修改配置文件,验证身份登录 (3)重启服务 (4)使用超级管理员登录 (5)创建普通用户 (6)使用普通用户登录对应的数据库 mongodb数据库角色: 1创建 ...

  2. LeetCode 2 :Swap Nodes in Pairs

    我的代码是这样的: class Solution { public: ListNode *swapPairs(ListNode *head) { ; ; ListNode *listA; ListNo ...

  3. Charles Android 抓包失败SSLHandshake: Received fatal alert: certificate_unknown

    前提: Android使用Charles抓取Https请求的报文时,Android和Charles都正确安装了证书之后出现抓包失败,报错SSLHandshake: Received fatal ale ...

  4. <asp:TextBox><asp:LinkButton><input button>调用后台方法后刷新页面

    <asp:TextBox><asp:LinkButton>服务器控件,执行后台方法,会回调加载js,相当于页面重新加载,刷新页面 <input button>不能直 ...

  5. 安装VMware Tools的步骤和那些坑

    背景环境:VMware workstation 12.5+Ubuntu16.04 首先VMware Tools在ubuntu中是及其不稳定的,也就是说,当你点击菜单栏中的install vmware ...

  6. td中嵌套table,让table完全填充父元素td

    <table width="100% " cellspacing=0 cellpadding=0 border=1 > <tr> <td style= ...

  7. 一次Ubuntu下的排雷记录

    起因 某天,发现一台服务器上出现了一个大量占用cpu资源的进程.尝试手动杀掉,但很快就会自动重新创建新的进程. 追查 用命令lsof -p 10316 查看其文件路径: 该进程文件夹/proc/103 ...

  8. 转载---sql之left join、right join、inner join的区别

    原文地址:http://www.cnblogs.com/pcjim/articles/799302.html sql之left join.right join.inner join的区别 left j ...

  9. 对数据访问层的重构(及重构中Perl的应用)

    以前上学的时候,听到“一个学生在毕业后刚刚开始编程的头几年中,写出的代码多半是垃圾”这样的说法,均不屑一顾.现在工作一年多了,越发感觉自己代码中疏漏处甚多,故近来常做亡羊补牢的重构之举.拿自己4个月前 ...

  10. 发布message给其他包使用

    https://answers.ros.org/question/65716/which-is-the-correct-way-to-install-header-files-in-catkin-pa ...