Thanks to asynchronous log services
Develop asynchronous log services using Hibernate and JMS
Summary
In software development, the log is a fairly important component, especially for the robustness of the software. Typically, log services are synchronized, which will bring additional performance overhead (especially in urgent situations). Such a log service cannot be effective as a distributed log service. In a distributed computing environment, such as J2EE, the client expects the log to record to the central database, the J2EE architecture does not advocate logging the log to the file or prints to the console. As an app for JMS, you can use asynchronous log services to replace the usual synchronization log service. This client can continue to execute without blocked. Under the reliable mode, log data is submitted ( And it is only submitted to a destination (Destination), next, log information will be easier to last for Hibernate. This article describes how to use Hibernate and JMS to develop an asynchronous log service.
text
Developing a general log service usually arguing. Now, there are already considerable log frameworks, which are developed by full-time person or open source community, and should be mentioned in the log4j and j2se1.4. Since many log frames are in JMS (Java Message Services - Java Message Service) has not yet been developed before, there is no asynchronous log. After the JMS came out, the frame was designed to use asynchronous logs.
In the traditional synchronization log model, the caller cannot be executed under the log service call without successful returns, and all the calles are blocked until the record is lasteded or received by the log service. Obviously, it will result in additional overhead, especially when an application is designed to record a large number of log information. Imagine a large (usually hundreds) log statements consisting, each log information should be completed before the next log is processed, which is a fairly time consuming process. In the distributed computing environment, the client is running concurrent, the optional method is to create a concurrent client using the traditional log service, although performance is a problem. The distributed computing framework is deployed to many servers (many local or non-similar parts), in which case the log-to-center database is quite cumbersome, and it is almost impossible.
This article will guide you to develop a simple log service. Create some log information, send it to the JMS provider over the network, and last forever. For this purpose, we use JMS to achieve asynchronous and use Hibernate to last for lasting data. You can have a variety of ways, such as a standard JDBC (Java Database Connectivity), EJB (Enterprise JavaBean), or stored procedure. I recommend using tools to create entity domains from traditional Pojo (Plain-Old Java Objects). In this article, I use hibernate to replace the entity model that is originally built in advance using EJB.
Before developing log services, let us understand some important concepts, these concepts are related to this application development.
Enterprise Javabean
J2EE About the distribution computing environment is also continuing to improve, we can add many of its characteristics, such as JMS to develop asynchronous services. JMS is a specification of the Sun micro system and is suitable for communication between standard applications. Reference resource section, download this specification, Third-Party Vendors implements this specification for Sun definitions. JMS is designed to handle different message types (messages do not need to know what they hold) Remote Procedure Call (RPC) model, such as RMI (remote method call -Remote Method Invocation), SOAP (Simple Object Access Protocol-Sme Object Access Protocol), ORB (Object Request Agent - Object Request Broker) is a central interface, meaning that the publisher expects a return value. In the JMS environment, the sender does not understand the recipient. The application of receiving and sending messages depends on a specific channel, but they do not communicate, in fact, they just be delegated to the transfer message to the JMS provider, after the application sends a message to the destination, their work is completed.
Message category
JMS offers two mandatory models, Porint-to-Porints and publish / subscribe. The point-on-point is a queue-based message model, and each client sends a message to a destination queue, which exists in a stack. The message can also be persisted to ensure that the server is still available when the server is operated. The JMS provider delivers the message to the stack to supply consumers. In point-to-point model, a message can only be delivered to a consumer. In the publish / subscription is a broadcast model, in this model, all clients interested in a particular topic, register themselves as a monitored. The publisher released its message to the destination (topic), and the JMS provider is responsible for distributing messages to these monitors. In this mode, all monitors will consume every message.
Message driver bean
EJB2.0 describes a new BEAN component type: message driver bean (MDB). This bean does not respond to the client's call. In fact, no interface is provided so that the client can call MDB. When a specific JMS message is received, only the container activates MDB. MDB is just a message consumer, and the execution of MDB is concise. All JMS management information is described in the deployment. In the onMessage function, the behavior of receiving and processing messages is performed in accordance with the deployment. View the resource section, get more MDBS information
Hibernate
Hibernate is an open source product for exemption from JDBC encoding. This is a tool for implementing OR mapping in the Java environment, which establishes mappings between Java objects and database entities. In enterprise development, object relationship mapping is a key requirement, or the resulting or modified data must be lasting. The data is lasting is a demand, especially multilateral, and the modification of the data model. Hiberante can reduce data lasting complications. View the resource section to learn more about Hibernate, this article describes the development of the log service, which will use Hibernate as the Or lasting medium.
Asynchronous log service
In the above sessions, I briefly introduced the main techniques you need to develop this log service. Let us now use JMS and Hibernate to develop a simple framework.
Summary, the asynchronous log service is working as follows: The client creates a log message logMessage (Value Object), requiring a secondary (JMSLogger) to publish this message to the queue. Auxloger uses log messages to create a JMS Object Message and submit it to the queue. Once the message arrives, the container calls the MDB listening to this queue and accesses its OnMessage callback method. MDB Read Message (LogMessage) and then uses Hibernate persistent messages to the database log service to use JMS point-to-point message. Once a log message is sent, the client does not need to worry about where the log message is sent, or if it is sent. The client trust JMS message mechanism to ensure that the message is delivered.
The following illustration shows the main components of the log service
Function framework: Main components of log services
Frame component
Before analyzing the details, let's take a closer look at these components, the logger is the entry point of this application, as a non-J2EE client, this is only a small difference with the J2EE client. The log program uses JMSLogger to send a message to the queue, which creates a log message (logmessage) and then sent by JMSLogger to the LogMessageQueue destination
JMSLogger is a JMS class that is instantiated, it is associated with yourself to the message destination. Therefore, when JMSLogger is created by the logger, it looks out through the JNIDI (Java Name Directory Access Interface -Java Naming and Directory Interface) Name Space (Queue), then open and JMS provider (JMS Provider Session (session), next, JMSLogger sends a message to the destination. Application client access log service via a simple instantiation log program and calls it. In the J2EE environment, the log service is instantiated when the application service is started. When the application service is started, use the JMX-Java Management Extensions to manage Beans so that the client can find this through JNDI. Service, then like the usual, call it to persistent log messages
LogMessageQueue is the destination sent by log messages, an MDB listening to this queue. Once the message reaches the queue, the EJB container calls MDB and delegates it makes more processing. MDB Removes Log Messages, passed through Hibrante's persistent mechanism, lasting log messages to the database.
LogMessage is a Java object that is lasteded with log information. It is designed to hold log information, such as a concise description, detailed description, log time and log level.
achieve
Now, I will detail the implementation of the log service. In the resource section, you can download all implementation code and then decompressed to the local directory.
Create a log form
Let us first create a table that stores log information. In the table, we only need to save log information as follows: Simple description, detailed description, log level, log time. Listing 1's script statement creates a log table named log_data, which has 5 data columns. In addition to Message_ID, other do not need to be explained, create this form of this form for this table for the script provided in the source source, which is related to the application. In the section of the Hibernate Mapping Files, I will tell.
Listing 1: Create a script for log form
Create Table Log_Data (Message_ID VARCHAR2 (30) Not Null, Short_Desc Varchar2 (20), Long_Desc Varchar2 (200), LOG_DATE DATE, LOG_LEVEL VARCHAR2 (10))
LogMessage class
LogMessage is a Value Object that is lasting to the log database. The logger creates this object with the appropriate log information. As mentioned earlier, I will use HiberaNte's lasting logMessage object.
Create a Java class based on the description of the previous table, I created a Java class with five attributes, each of which corresponds to a data column of the log table, and also creates setters and getters methods for each attribute, because Hibernate needs these methods.
Hibernate or mapping file
Hibernate needs to map files to persistence LogMessage. As written by this section, the mapping file defines the object-relational mapping. In our needs, it defines the mapping of logMessage properties and log tables. The syntax of this XML mapping file is easy to understand.
Listing 2: Hibernate or mapping file
The first line of the file (
JMS log bean -jmsloggerbean (mdb)
JMSLoggerBean listens to the queue reached by the message, lasting message to the database. Once the message arrives, the container calls JMSLoggerBean. In the onMessage () method, the MDB requests the Hibernate persistent message object. Because of Hibernate's simplified persistent data, I don't need to pass messages to other components, such as session bean (session beans) to do one step. MDB can do all the things handled.
OnMessage () method looks like this:
public void onMessage (javax.jms.Message message) {try {// Cast the JMS message to ObjectMessage type ObjectMessage objMsg = (ObjectMessage) message; // And extract the log message from it LogMessage logMsg = (LogMessage) objMsg.getObject ( ); // persist the message persistMessage (LogMsg);} catch (exception t) {t.printStackTrace ();}}
Once the message reaches the queue, the container calls the MDB onMessage method. In this method, the logMessage is obtained from the JMS Object Message (Object Message is a category of the message), and the following method is lasting.
private void persistMessage (LogMessage message) throws HibernateException {net.sf.hibernate.Session session = null; SessionFactory sessionFactory = null; Transaction tx = null; try {// Create a session factory from the configuration (hibernate.properties // File should be present in the class path) sessionFactory = new Configuration () addClass (LogMessage.class) buildSessionFactory ();.. // Create a session session = sessionFactory.openSession (); // Begin a transaction tx = session.beginTransaction () ;} Catch (..) {.....} try {// assign the message ID message.setMessageId (" system.currenttimemillis ()); // save the object to the database and commit the transaction session. Save (Message); tx.commit ();} catch (exception ex) {....} finally {// close the session session.close ();}} In the first try-catch block, sessionFactory object Created, it opened a session to the database, I created a transaction from this session
SessionFactory = new configuration (). addclass (logmessage.class). BuildSessionFactory (); session = sessionFactory.opensesis (); tx = session.begintransaction ();
In the next try-catch block, the id is assigned to the logMessage object, then the logMessage object is lasting (saved) to the database, as follows:
Message.SetMessageId (" system.currenttimemillis ()); // save the object to the database. session.save (message); tx.commit ();
As you can see, once you create an object-relational map file, lasting log information will become very easy, Hiberante completed all the processing in the background.
Deployment Descriptor
The deployment is as follows, Listing 3 is an EJB-JAR.XML file, and LISTINGS 4 and 5 is a specific deployment of JBoss and JRun.
Listing 3: EJB-JAR.XML Deployment Description
....
Listing 5: JRUN Deployment Description
....
You can download all of these deployments from the resource section Description Client Code
Next start coding development client program: JMSLogger, LogService and Logger, these classes for client interaction
JMSLogger is a program that sends a message. LogService calls its constructor to instantiate, constructor needs to connect the name of the factory and destination as a parameter.
Logger logger = new JMSLogger ("ConnectionFactory", "Queue / CyrusLogqueue");
Once JMSLogger is instantiated, logService only needs to call the SendMessage method, the code is as follows:
private void sendMessage (LogMessage logMessage) {JMSLogger logger = null; .... logger = new JMSLogger ( "ConnectionFactory", "queue / CyrusLogQueue"); ... logger.sendMessage (logMessage); System.out.println ( " [Logservice :: sendMessage: The message Sent] "); ....}
Logger is a category that is wound around LogService and is called by the client. The client creates the way the Logger Logger Logger = New Logger () and then calls it.
Deploying Bean
Before accessing the log service, deploy MDB's JAR to the application server, create queues and connecting factories. In JBoss, you can create these objects managed by the JMS in two ways, by using the console or write your own destination to the XML file (create
If you are using JRUN, you create these objects by editing JRun-resources.xml or using the console.
Please understand the deployment of JBoss and JRun in the resource part.
Use log service
A simple way to use the log service is to initialize the logger at the client, once initialized, the log method can be called, as follows
try {Logger logger = new Logger (); logger.info ( "MSG000111", "CONFIG SEVICE is not initialised Please check the settings..");. logger.severe ( "ERR101010", "APPSERVER CRASHED Notification to the Admin sent Catch (LOGEXCEPTION LEX) {....}
Some JUnit tests can test this service, unzip the logservicetestcase.java and logservicetestsuite.java test files in the resource.
to sum up
This article introduces how to develop an asynchronous log service. JMS is a powerful feature of J2EE. JMS's asynchronous behavior and HiberaNTe's object-relational mapping provide a reliable and flexible framework. A lot of Java application-dependent protocols, such as RMI, SOAP, CORBA, can expand by using JMS. After EJB 2.0, the EJB can utilize a message model from the framework of JMS to the application service. A message agent called the session bean is replaced by the message driver bean. Asynchronous message service principles can be applied to many services. For example, attribute services, configuration services, and other data services. Manage Beans by using JMX, the asynchronous log service described by this article can be configured. Of course, you can also create a log browser to browse the log information lasting to the database.
Resources:
Download the asynchronous log service: http://www.javaworld.com/javaworld/jw-05-2004/logging/jw-0510-logging.zip
Read The Java Message Service (JMS) Specification from Sun: http://java.sun.com/products/jms/docs.html
FOLLOW this link to jumpstart hibernate: http://www.hibernate.org/152.html
One of the good books to read about JMS: Java Message Service, Richard Monson-Hafel and David Chappell (O'Reilly & Associates, December 2000; ISBN: 0596000685): http://www.amazon.com/exec/obidos/ Asin / 0596000685 / JavaWorld
Sun's JMS Page: http://java.sun.com/products/jms/index.html
Download jboss 3.2.3 from here: http://www.jboss.org/downloads
Download Jrun4 (Trial Version, Requires Registration): http://www.macromedia.com/cfusion/tdrc/index.cfm?Product=jrun
Some useful and interesting external articles related to hibernate is found here: http://www.hibernate.org/78.html
Shaun Terry's book Enterprise JMS Programming is a good book for advanced JMS programming (John Wiley & Sons, February 2002; ISBN: 0764548972): http://www.amazon.com/exec/obidos/ASIN/0764548972/javaworld
Scott Stark's "How To Integrate Custom Services Via MBeans": http://www.huihoo.com/jboss/online_manual/3.0/ch13s26.html
Macromedia's Jrun Services: http://livedocs.macromedia.com/jrun/4/jrun_sdk_guide/creatingservices3.htm
For more articles on JMS, browse the Java Message Service (JMS) section of JavaWorld's Topical Index: http://www.javaworld.com/channel_content/jw-message-index.shtml?For more articles on JDBC, EJB, and JNDI Browse the Enterprise Java Category of JavaWorld's Topical Index: http://www.javaworld.com/channel_content/jw-enterprise-index.shtml