[转] JNDI role in J2EE - release you from trouble

xiaoxiao2021-03-06  18

Transfer from: http://www-900.ibm.com/developerWorks/cn/java/j-jndi/index.shtmlkirk PepperDine (Kirk@javaperformancetuning.com), Chief Technology, Javaperformancetuning.com

Joseph Ottinger

(Joeo@enigmastation.com), Consultant January 2005

Mastering J2EE is a daunting thing because it contains technology and abbreviations constantly grow. Java Naming and Directory Interface (JNDI) has always been the core of Java 2 Platform Enterprise (JEE) from the beginning, but J2EE develops novices often use it. This article will eliminate the mystery of JNDI playing roles in the J2EE application and showing how it helps apps from deployment details.

Although the J2EE platform improves the living standards of ordinary enterprise developers, this improvement is to integrate J2EE to become a distributed computing platform for unparalleled distributed computing platforms. Incoming. Dolly Developer is a member of many developers, she has discovered a feature that helps to alleviate the burden of deployment of enterprise applications, this feature is JNDI, Java Named Directory Interface (Java Naming) And Directory Interface). Let's take a look at how dolly does doing JNDI, and how she correctly applies JNDI to improve its situation.

Everyone is very familiar with Journey Dolly Developer is writing a web application that uses JDBC data sources. She knows that she is using MySQL, so she encodes a reference to the MySQL JDBC driver class and connects to the database in its web application with the appropriate JDBC URL. She realized the importance of the database connection pool, so she contains a connection pool package and configures it to use up to 64 connections; she knows that the database server has been set to allow 128 clients to connect.

Dolly is going to disaster in the development phase, each matter is going well. However, when deployed, starting out of control. Dolly's network administrator tells her that she can't access the production server or the Staging Server from her desktop, so she has to develop different code versions for each deployment phase. Because of this situation, she needs a new JDBC URL, so they have to deploy independently for testing, phases and production. (One heard of the establishment of separate deployments in each environment, those who are familiar with configuring management will fight, but since this is a very common situation, they have only hard my scalp.)

Just in Dolly believes that the independent deployment of different URLs has resolved their own configuration issues, she found that her database administrator did not want to run the MySQL instance in the production environment. He said that mysql is used as development, but for task key data, the business standard is DB2®. Now her construction is not only different in database URLs, but also different drivers.

The more it is getting worse. Her app is very useful and it becomes very critical, so that it gets fault recovery from the application server and copied to 4 server clusters. However, the database administrator proposed protests because each instance of her app uses 64 connections, and the database server has only 200 available connections - all are occupied by Dolly's applications. What is more trouble is that DBA has determined that Dolly's application only needs 32 connections, and only one hour is used once a day. As her application scale expands, the application encounters database-level contention problems, and her only choice is to change the number of connections to the cluster, but also prepare, in the number of cluster growth or application to another. Take another operation again when the cluster is clustered. It seems that she has decided how to configure applications, the application's configuration is best to leave it to system administrators and database administrators. J2EE's role If Dolly understands the role played by J2EE when developing an application, then she may avoid encountering this kind of dilemma. The J2EE specification delegates responsibilities to multiple development roles: Component Provider, Application Assembler, Deployer (Deployer), and System Administrator. (In many companies, the role of the component provider and component assembly is integrated, the role of deployers and system administrators is integrated together.) Master the J2EE role before you really understand the JDI role in J2EE. It is very important.

Component provider

This role is responsible for creating J2EE components, the J2EE component can be a web application, an enterprise-level JavaBean (EJB) component, or an application client (such as Swing GUI client applications). Component providers include: HTML designers, document programmers, and other developers. Most J2EE developers spend considerable time on the role of component providers.

Application assembly

This role is bundled with a plurality of J2EE modules into one other, and can be deployed as a whole: Enterprise Archive (EAR) file. Application assembly is to select components to distinguish between interacts between them, configure their security and transaction properties, and package applications into the EAR file. Many IDEs, such as WebSphere® Studio, IDEA, JBUILDER, WebLogic Workshop, and other IDEs, can help the application assemblers configure an EAR file in interactive.

Deployer (Deployer)

This role is responsible for deploying, which means installing the EAR into the J2EE container (application server), then configures resources (eg, database connection pool), binding the resources required by the application to specific resources in the application server, and start the application program.

System administrator

This role is responsible for ensuring that resources needed by the container can be used for containers.

Role Batters have an enterprise application that contains a web application, as well as EJB components responsible for business logic and persistence. There are many components vendors developing this app, but in many cases, you can assume all your duties. Components can include data transfer objects (a JAR file), EJB interface (another JAR file), EJB implement itself (another JAR file), and user interface components - servlet, JSP, HTML pages, and other static web content. The user interface component is further packaged into a web application, which contains the servlet class, JSP files, static content, and JAR (including EJB interfaces) of other required components. This sounds like it is too much to use, almost exceeded the scope of people, especially when considering how many JAR files that need to build a typical web application. However, it is important to recognize that it must manage dependencies here. Interfaces and transfer objects are web applications and EJB implementations that can rely on, but the direction of dependence should be the same; also avoiding loop dependence. J2EE components (such as WAR files and EJB JAR files) must declare their dependence on their deployment units.

Application assemblers are responsible for inclusion of dependencies in the web application and package them as a whole into a single enterprise application. The tool is here helpful. IDE can help create project structures that reflect modules and JAR dependencies, allowing you to specify or exclude modules.

The deployment personnel are responsible for ensuring the resources required to exist in the deployment environment and bind components to the available resources of the platform. For example, an external EJB reference in a web application (EJB-REF in the deployment descriptor) is the EJB component that is bound to actual deployment at this time - and is immediately bound.

The Nontrivial J2EE application needs to access information that describes it expects the environment. This means that when developing and testing the components, for temporary testing code, developers should assume some responsibilities of deployment. It is important to understand: When you do it, you have gone out of the field of developers. Otherwise, you can try to rely on the JDBC driver, or the URL, JMS queue name, or other unconscious, occasionally a machine resources that may be catastrophic.

JNDI comes to assisting Dolly issues is to clear all direct references to data storage from her application. There is no reference to the JDBC driver, no server name, no user name or password - even there is no database pool or connection management. Dolly needs to write code to ignore the specific external resources that will be accessed, just know that others will provide links needed to use these external resources. This allows deployment (any person in this role) to assign database connections to Dolly's applications. Dolly is not necessary to participate. (From the database security to the Sarbanes-Oxley bill, she has not participated in it, and she also has sufficient business reasons.)

Many developers know that the tight coupling between code and external resources is a potential problem, but in practice, it often forgets the division of roles. In small development work (referring to a team size or deployment size), it can be successful even if it is ignored. (After all, if the app is just a personal application, and you are not prepared to rely on it, it is also very good to lock the application on a specific PostgreSQL instance.)

The J2EE specification requires all J2EE containers to provide the implementation of JNDI specifications. JNDI's role in J2EE is the "switch" - J2EE component to find a general mechanism for other components, resources, or services in run time. In most cases, the container that provides JNDI suppliers can act as limited data storage so that the administrator can set the execution attribute of the application, and let other applications reference these properties (Java Management Extensions, JMX) Can be used as this purpose). JNDI's main role in the J2EE application is to provide an interior layer, which can find the resources required without understanding these indirectivity. Dolly's situation is worse, now let's take a look at Dolly's situation. In its simple web application, she uses a JDBC connection directly from the application code. See List 1, we can see that Dolly explicitly encode the JDBC driver, database URL, and her username and password to servlet:

Listing 1. Typical (but bad) JDBC usage

Connection conn = NULL;

Try {

Class.Forname ("com.mysql.jdbc.driver",

True, thread.currentthread (). getContextClassLoader ());

CONN = DriverManager.getConnection ("JDBC: MySQL: // DBServer? User = Dolly & Password = Dagger");

/ * Use the connection here * /

C. close ();

}

Catch (Exception E) {

E.PrintStackTrace ();

}

Finally {

IF (conn! = null) {

Try {

CONN.CLOSE ();

} catch (sqlexception e) {}

}

}

If you don't need to specify configuration information, Dolly (and her companions) use JNDI to find JDBC DataSource better, as shown in Listing 2:

Listing 2. Get data sources using JNDI

Connection conn = NULL;

Try {

Context ctx = new initialContext ();

Object DataSourceRef = ctx.lookup ("java: comp / env / jdbc / mydatasource");

DataSource DS = (Datasource) DatasourceRef;

CONNECTION C = ds.getConnection ();

/ * Use the connection * /

C. close ();

}

Catch (Exception E) {

E.PrintStackTrace ();

}

Finally {

IF (conn! = null) {

Try {

CONN.CLOSE ();

} catch (sqlexception e) {}

}

}

In order to get a JDBC connection, you must first perform some small deployment configuration so that we can find DataSource in the JNDI of the local component. This may be a bit cumbersome, but it is easy to learn. Unfortunately, this means that even if it is for testing components, developers must also be involved in deployment personnel, and also prepare to configure application servers.

Configuring JNDI reference To make JNDI parsing Java: Comp / Env / JDBC / MyDataSource reference, deployers must insert the tag into the web.xml file (the deployment descriptor of the web application). The meaning of the label is "This component is dependent on external resources". Listing 3 shows an example: List 3. Resource-Ref entry

Dollys DataSource

JDBC / MyDataSource

javax.sql.datasource

container

The entry tells the servlet container, and the deployment will set a resource called JDBC / MyDataSource in component name context (Component Naming Context). Component Name Context By Prefix Java: Comp / ENV / Represents, the fully qualified local resource name is: Java: Comp / Env / JDBC / MyDataSource.

This is only defined to the local reference to external resources, and there is no actual resource that reference points to. (In the Java language, similar situations may be: declares a reference, such as Object Foo, but not set foo to actually reference any Object.)

The work of deployment is to create DataSource (or create an Object object, let Foo point to it, in our Java language example). Each container has a mechanism for setting a data source. For example, in JBOSS, it is a service to define a data source (see $ jboss / server / default / deploy / hsqldb-ds.xml, use it as an example), which specifies yourself is a Global JNDI name of DataSource (by default It is defaultds. After the resource is created, the third step is still critical: connect the resource connection or bind to the local name used by the application component. In the case of using a web application, this binding is displayed using the vendor-specific deployment descriptor extension, and one such example is displayed in Listing 4. (JBoss is deployed as a vendor-specific web application deployment descriptor as a file called JBoss-Web.xml.)

Listing 4. Bind resources to the JDI name with the supplier's deployment descriptor

JDBC / MyDataSource

Java: Defaultds

This indicates that the local resource reference name (JDBC / MyDataSource) is mapped to the global resource named Java: DefaultDS. If the global resource name has changed for some reason, the application's code does not need to change, then simply modify this mapping. Here, there are two levels of indirect addressing: a definition and name resource (Java: DefaultDS), another resource that binds the name-specific name (JDBC / MyDataSource) to a naming resource. (In fact, when you reflect the resource at the EAR level, there may be a third level of indirect addressing.) Beyond the data source. The resources in J2EE are not limited to JDBC data sources. There are many types of references, including resource references (already discussed), environmental entities and EJB references. Especially EJB references, it exposes another key role in JNDI in J2EE: Find other application components.

Imagine this situation: What happens when a company purchased a deployable EJB component from Order Ontology Processing Services (OOPS) to handle customer orders. For ease of illustration, we call it ProcessRDERS V1.0. ProcessRDERS 1.0 has two parts: a set of interfaces and support classes (Home and Remote interface, and supported transfer class); actual EJB component itself. Select OOPS because it is professional in this area.

The company complies with the J2EE specification to write a web application referenced by EJB. The company's deployment personally binds ProcessOrDERS 1.0 to the JNDI tree, uses it as EJB / ProcessRDERS / 1.0, and parses the resource name of the web application to point to this global JNDI name. So far, these are very common usual uses of EJB components. However, when we consider interaction between the company's development cycle and the company's supplier, things become complicated. Here, JNDI can help us.

We assume that OOPS releases a new version, which is ProcessRDERS V1.1. This new version has some new features, a new application within the company needs these new features, and naturally expands the business interface of the EJB component.

Here, the company has the following options: You can update all applications to use new versions, or write your own version, or use JNDI reference parsing, allowing each application to use themselves without affecting other applications. EJB component version. Immediately update all applications a nightmare for maintenance, which requires full regression testing for all components, which is often a daunting task, and if any function test fails, then another Round debug.

Writing an internal (in-house) component is often unnecessary. If the component is written by a company with expertise in this business, then a given IT store is unusually proficient in business functions as a professional component vendor.

As you may have already guess, the best solution is to analyze JNDI. EJB's JNDI reference is very similar to a reference to JDBC resources. For each reference, the deployment needs to bind the new component to the global tree by specific name (such as EJB / ProcessRDERS / 1.1), and for each other of the EJB component, the component is deployed in deployment descriptor Analysis of EJB references. Depending on the application of V1.0 does not need to make any modifications, it does not require re-test, which shortens the time of implementation, reduces cost and reduces complexity. This is a very effective way in the environment that tends to conversion. This type of configuration management can be performed on all components obtained in the application architecture, from EJB components to JMS queues and topics, and then to simple configuration strings, or other objects, which can reduce the maintenance costs generated by over time. At the same time, you can simplify deployment and reduce integration. Conclusion There is an ancient computer science joke: each programming problem can be solved only with an abstract layer (or indirect). In J2EE, JNDI is an adhesive that combines J2EE applications, but it has not been tight to unable to separate them and re-assemble them. The indirect address provided by JNDI allows you to deliver scalable, powerful and flexible applications across enterprises. This is a commitment of J2EE, and after some plans and pre-considerations, this commitment is fully implemented. In fact, it is much easier than many people.

Reference

You can see this article in our website on our world. From Sun Microsystems, the JNDI Tutorial can learn more JNDI knowledge. "USING JNDI OUTSIDE J2EE" is taken from Teach YourSelf J2EE in 21 Days (Sams Publishing, 2004), demonstrating how to define the name service type being used, and how to define the host name and port number of the server on the network. DEVELOPERWORKS column writer Brian Goetz discussed how to use JNDI and J2SE for application configuration using JNDI and J2SE in his article "J2EE or J2SE? JNDI WORKS WITH BOTH" (JavaWorld, April 2002). Daniel shows how to "get out of JNDI maze" by explaining JNDI name context used in J2EE applications. The JNDI is used for WebSphere Application Server J2EE thin client applications to show how JNDI is using JNDI in the J2EE application client to communicate with the remote JNDI provider. Hundreds of technical articles about Java are found in the DeveloperWorks Java technology area. Please visit developer bookstore to get a full list of technical books, including hundreds of Java-related topics.

About the author Kirk PepperDine is the Chief Technology Officer of JavaperformancetUning.com, and he has been focusing on object technology and performance adjustment over the past 15 years. He is also one of the owners of the Ant Developer's Handbook (Macmillan).

转载请注明原文地址:https://www.9cbs.com/read-64037.html

New Post(0)