Тема: Скрипты
Показать сообщение отдельно
Непрочитано 29.01.2009, 20:23   #4
Аватар для VISTALL
Illussion is real

Автор темы (Топик Стартер) Ответ: Скрипты

интересно Согласен. ну то что поднапрячся с кодом. Мне не страшно я уже поигрался с переходом на постгрес. ThreadConnection и L2DatabaseFactory у ребы другие... Хоча можно перейди с c3p0 библиотекы конекта и так далее . Вопрос стоит ли?

Добавлено через 5 минут
ребелионовська L2DatabaseConnection
Код:
package l2r.database;

import java.sql.SQLException;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;

import l2r.Config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;

/**
 * <p>При работе с пулами коннектов иногда возникает ситуация - когда выбираешь весь пул до предела и
 * при этом коннекты не закрываются а требуется получить еще один коннект. В этом случае программа
 * зависает. Так бывает если в процессе выполнения одного запроса при переборке результатов вызывается
 * другая функция, которая также берет коннект из базы данных. Таких вложений может быть много. И коннекты
 * не отпускаются, пока не выполнятся самые глубокие запросы. DBCP и C3P0 висли при этом - опробовано на
 * практике.
 * </p>
 * <p>Для того чтобы избежать этой коллизии пишется оболочка для коннекта, которой коннект
 * делегирует все свои методы. Эта оболочка хранится в локальном пуле коннектов и если коннект запрашивается
 * в потоке - для которого был уже открыт коннект и еще не закрыт, то возвращаем его.
 * </p>
 * Эту возможность можно отключить выставив в настройках сервера UseDatabaseLayer = false;
 */
public class L2DatabaseFactory
{
	private static L2DatabaseFactory _instance;
	private ComboPooledDataSource _source;

	//список используемых на данный момент коннектов
	private final Hashtable<String, ThreadConnection> Connections = new Hashtable<String, ThreadConnection>();

	static Logger _log = Logger.getLogger(L2DatabaseFactory.class.getName());

	public L2DatabaseFactory() throws SQLException
	{
		_instance = this;
		try
		{
			if(Config.DATABASE_MAX_CONNECTIONS < 2)
			{
				Config.DATABASE_MAX_CONNECTIONS = 2;
				_log.warning("at least " + Config.DATABASE_MAX_CONNECTIONS + " db connections are required.");
			}

			Class.forName(Config.DATABASE_DRIVER).newInstance();

			if(Config.DEBUG)
				_log.fine("Database Connection Working");

			_source = new ComboPooledDataSource();
			_source.setDriverClass(Config.DATABASE_DRIVER); //loads the jdbc driver
			_source.setJdbcUrl(Config.DATABASE_URL);
			_source.setUser(Config.DATABASE_LOGIN);
			_source.setPassword(Config.DATABASE_PASSWORD); // the settings below are optional -- c3p0 can work with defaults
			_source.setAutoCommitOnClose(true);
			_source.setInitialPoolSize(1);
			_source.setMinPoolSize(1);
			_source.setMaxPoolSize(Config.DATABASE_MAX_CONNECTIONS);
			_source.setAcquireRetryAttempts(0);// try to obtain Connections indefinitely (0 = never quit)
			_source.setAcquireRetryDelay(100);// 500 miliseconds wait before try to acquire connection again
			_source.setCheckoutTimeout(0); // 0 = wait indefinitely for new connection
			_source.setAcquireIncrement(5); // if pool is exhausted, get 5 more Connections at a time
			_source.setMaxStatements(100);
			_source.setIdleConnectionTestPeriod(60); // test idle connection every 1 minute
			_source.setMaxIdleTime(600); // remove unused connection after 10 minutes
			_source.setNumHelperThreads(5);
			_source.setBreakAfterAcquireFailure(false);

			/* Test the connection */
			_source.getConnection().close();
		}
		catch(SQLException x)
		{
			if(Config.DEBUG)
				_log.fine("Database Connection FAILED");
			// rethrow the exception
			throw x;
		}
		catch(Exception e)
		{
			if(Config.DEBUG)
				_log.fine("Database Connection FAILED");
			throw new SQLException("could not init DB connection:" + e);
		}
	}

	public static L2DatabaseFactory getInstance() throws SQLException
	{
		if(_instance == null)
			new L2DatabaseFactory();
		return _instance;
	}

	public ThreadConnection getConnection() throws SQLException
	{
		ThreadConnection connection;
		if(Config.USE_DATABASE_LAYER)
		{
			String key = generateKey();
			//Пробуем получить коннект из списка уже используемых. Если для данного потока уже открыт
			//коннект - не мучаем пул коннектов, а отдаем этот коннект.
			connection = Connections.get(key);
			if(connection == null)
				try
				{
					//не нашли - открываем новый
					connection = new ThreadConnection(_source.getConnection());
				}
				catch(SQLException e)
				{
					_log.warning("Couldn't create connection. Cause: " + e.getMessage());
				}
			else
				//нашли - увеличиваем счетчик использования
				connection.updateCounter();

			//добавляем коннект в список
			if(connection != null)
				synchronized (Connections)
				{
					Connections.put(key, connection);
				}
		}
		else
			connection = new ThreadConnection(_source.getConnection());
		return connection;
	}

	public int getBusyConnectionCount() throws SQLException
	{
		return _source.getNumBusyConnectionsDefaultUser();
	}

	public int getIdleConnectionCount() throws SQLException
	{
		return _source.getNumIdleConnectionsDefaultUser();
	}

	public Hashtable<String, ThreadConnection> getConnections()
	{
		return Connections;
	}

	public void shutdown()
	{
		_source.close();
		Connections.clear();
		try
		{
			DataSources.destroy(_source);
		}
		catch(SQLException e)
		{
			_log.log(Level.INFO, "", e);
		}
	}

	/**
	 * Генерация ключа для хранения коннекта
	 *
	 * Ключ равен хэш-коду текущего потока
	 *
	 * @return сгенерированный ключ.
	 */
	public String generateKey()
	{
		return String.valueOf(Thread.currentThread().hashCode());
	}
}
Цитата:
Вот непойму, почему все гонятся за обновлениями то?!
По теме, пСКЛ это замечательно, но МС былоб лучше
А в чём проблема со скриптами?На просторах всё есть и без хайда
Ну если что, пиши в аську ( есть в профиле ) помогу чем смогу
я не гонюсь просто полезные функции.
НУу ч то с Лог сервером то ищо долго даже хоть до бета реализа.
Хочу сделать норм серв под х1 рейты гдето

Добавлено через 10 минут
Aquanox

Hibernate Core
An excellent Java framework, the Hibernate project provides nearly transparent persistence for Java classes. It supports association, inheritance, polymorphism, composition, and the standard Java collection classes. Instead of invasive inheritance, manual interface implementation, code generation, or post-processing, Hibernate uses run-time reflection at system initialization to generate SQL and proxy implementations.

The API and query language (HQL) have the object-oriented feel of Versant, yet Hibernate supports blazing fast access to MySQL Server, PostgreSQL, Oracle, DB2, and many other relational databases. Hibernate works well both inside and outside of application servers. Many programmers are beginning to consider Hibernate as a preferred alternative to CMP in J2EE environments.

Spring Framework
The Spring project provides a layered Java/J2EE application framework based on code published in Expert One-on-One J2EE Design and Development by Rod Johnson (Wrox, 2002). The Spring Framework includes:

A complete lightweight container, providing centralized, automated, and transparent configuration and wiring of your application objects.

A common abstraction layer for transaction management, allowing for pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. In contrast to plain JTA or EJB CMT, Spring's transaction support is not tied to any J2EE environment.

A JDBC abstraction layer that simplifies error handling and greatly reduces the amount of code you need to write.

Integration with Toplink, Hibernate, JDO, and iBATIS SQL Maps.

First-class Hibernate support with lots of IoC convenience features, addressing many typical Hibernate integration issues.

Fully integrated AOP functionality meaning you can AOP-enable any object managed by Spring. For example, you can have declarative transaction management without EJB, even without JTA, if you're using a single database in Tomcat or another web container without JTA support.

A flexible MVC web application framework. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI.

The ability to combine a Spring middle tier with any other web MVC framework, like Struts, WebWork, or Tapestry.

A layered architecture so that each piece of functionality builds on lower levels. So you can use the JavaBeans configuration management without using the MVC framework or AOP support. But if you use the MVC framework, because it builds on the configuration framework, you can apply knowledge about configuration management to the MVC framework immediately.

Use Spring's functionality in any J2EE server, and most of it also in non-managed environments. A central focus of Spring is to allow for reusable business and data access objects that are not tied to specific J2EE services. Such objects can be reused across J2EE environments (web or EJB), standalone applications, test environments and the like without any hassle.

Мне уже нравится.можно посмотреть

Последний раз редактировалось DarkLoki; 03.02.2009 в 13:15. Причина: Добавлено сообщение
VISTALL вне форума Ответить с цитированием