日期:2014-05-16  浏览次数:20582 次

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!