JPPF Task类中做到重复使用一个数据库连接池(或者其他重量的对象)

我们可能会在有一些JPPF task中需要连接到数据库, 但是我们又不能把connection作为JPPFTask的参数或者属性(因为Connection不能序列化). 这样的化我们就只能在JPPFTask里的run方法中去创建连接. 因为我们可能有很多JPPF节点.而且每个节点也可能会的接受到很多次task. 所以就会造成频繁的创建Connection. Mysql很快的就会撑不住了.

下面介绍一个类用来解决这种问题.

Class: org.jppf.node.NodeRunner


/**
* Bootstrap class for lauching a JPPF node. The node class is dynamically loaded from a remote server.
* @author Laurent Cohen
*/
public class NodeRunner
{
//***************
/**
* Set a persistent object with the specified key.
* @param key the key associated with the object's value.
* @param value the object to persist.
*/
public static synchronized void setPersistentData(Object key, Object value)
{
persistentData.put(key, value);
}

/**
* Get a persistent object given its key.
* @param key the key used to retrieve the persistent object.
* @return the value associated with the key.
*/
public static synchronized Object getPersistentData(Object key)
{
return persistentData.get(key);
}

/**
* Remove a persistent object.
* @param key the key associated with the object to remove.
* @return the value associated with the key, or null if the key was not found.
*/
public static synchronized Object removePersistentData(Object key)
{
return persistentData.remove(key);
}

//******************

}


NodeRunner有2个static方法可以保存你想要persist的object,还有把你保存的对象拿出来.

下面贴一段代码看看怎么使用这个类..


public class XXXXXXXXXTask extends JPPFTask{


private static final String DATA_SOURCE_KEY = "dataSource";

public void run() {

DataSource dataSource = (DataSource) NodeRunner.getPersistentData(DATA_SOURCE_KEY);

XXXXXService service = null;

if (dataSource == null) {
dataSource = new DriverManagerDataSource("com.mysql.jdbc.Driver", "jdbc:mysql://192.168.1.90:3306/xxxx?useUnicode=true&characterEncoding=UTF-8", "xxx", "xx");
service = new XXXXXService();
service.setDataSource(dataSource);
NodeRunner.setPersistentData(DATA_SOURCE_KEY);

/ Process the task using the Service build from the dataSource./
}

}


OK!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值