Terracotta兵马俑集群-HelloWorld
一. 目的:
让两个独立的进程实现共同访问一个资源。
二. 先写一个demo:
源码:
package simpleparallel; public class Main implementsRunnable{ private Objectlock = newObject(); private int count = 0; private static Main inst = new Main(); /** * @param args */ public static void main(String[] args) { new Thread(inst).start(); new Thread(inst).start(); } public void run() { //keep increasing count by one every fewseconds while(true){ synchronized(lock){ count++; System.out.println(Thread.currentThread().getName() +" increased count to:"+count); } try{ Thread.sleep((int)(5000*Math.random())); } catch(Exception e){ e.printStackTrace(); } } } }
用两个进程运行后,很明显各自处理各自的事,没有一点联系。
三. 安装terracotta
运行terracotta-3.7.7-2013-08-19_16-03-48-installer.jar 进行安装,我安装在了d盘的terracotta目录,随后将Main类打包成main.jar,再新建一个tc-config.xml文件,文件内容如下:
<?xmlversion="1.0" encoding="UTF-8"?> <tc:tc-configxmlns:tc="http://www.terracotta.org/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.terracotta.org/schema/terracotta-6.xsd"> <servers> <server host="%i"name="localhost"> <dso-port>9510</dso-port> <jmx-port>9520</jmx-port> <data>/terracotta/server-data</data> <logs>/terracotta/server-logs</logs> <statistics>/terracotta/cluster-statistics</statistics> </server> </servers> <clients> <logs>/terracotta/client-logs</logs> </clients> <application> <dso> <instrumented-classes> <include> <class-expression>simpleparallel.Main</class-expression> </include> </instrumented-classes> <roots> <root> <field-name>simpleparallel.Main.inst</field-name> </root> </roots> <locks> <autolock> <method-expression>voidsimpleparallel.Main.run()</method-expression> <lock-level>write</lock-level> </autolock> </locks> </dso> </application> </tc:tc-config>
最后将tc-config.xml以及main.jar拷贝到terracotta的安装目录下,如下图所示:
启动 terracotta服务
保持界面不关闭,然后再调出两个cmd界面,运行Main.jar,
注意:terracotta-3.7.7-2013-08-19_16-03-48-installer.jar 需要的jdk版本是1.6,如果发现报错运行不成功,请检查jdk版本。
如上图所示,两个独立的进程可以共同访问count的资源了。
terracotta-3.7.7-2013-08-19_16-03-48-installer.jar 免费下载地址: http://download.csdn.net/detail/qq_27063119/9712109