Contidos dentroLocalizar Mais DocumentaçãoDestaques de Recursos de Suporte | Fazer download desta apostila em PDF (2033 KB)
Part III Using Services and APIsChapter 15 Using the JDBC API for Database AccessThis chapter describes how to use the JavaTM Database Connectivity (JDBCTM) API for database access with the Sun Java System Application Server. This chapter also provides high level JDBC implementation instructions for servlets and EJB components using the Application Server. If the JDK version 1.6 is used, the Application Server supports the JDBC 4.0 API, which encompasses the JDBC 3.0 API and the JDBC 2.0 Optional Package API. The JDBC specifications are available at http://java.sun.com/products/jdbc/download.html. A useful JDBC tutorial is located at http://java.sun.com/docs/books/tutorial/jdbc/index.html. Note – The Application Server does not support connection pooling or transactions for an application’s database access if it does not use standard Java EE DataSource objects. This chapter discusses the following topics: General Steps for Creating a JDBC ResourceTo prepare a JDBC resource for use in Java EE applications deployed to the Application Server, perform the following tasks: For information about how to configure some specific JDBC drivers, see Configurations for Specific JDBC Drivers in Sun Java System Application Server 9.1 Administration Guide. Integrating the JDBC DriverTo use JDBC features, you must choose a JDBC driver to work with the Application Server, then you must set up the driver. This section covers these topics: Supported Database DriversSupported JDBC drivers are those that have been fully tested by Sun. For a list of the JDBC drivers currently supported by the Application Server, see the Sun Java System Application Server 9.1 Release Notes. For configurations of supported and other drivers, see Configurations for Specific JDBC Drivers in Sun Java System Application Server 9.1 Administration Guide. Note – Because the drivers and databases supported by the Application Server are constantly being updated, and because database vendors continue to upgrade their products, always check with Sun technical support for the latest database support information. Making the JDBC Driver JAR Files AccessibleTo integrate the JDBC driver into a Application Server domain, copy the JAR files into the domain-dir/lib directory, then restart the server. This makes classes accessible to all applications or modules deployed on servers that share the same configuration. For more information about Application Server class loaders, see Chapter 2, Class Loaders. Creating a Connection PoolWhen you create a connection pool that uses JDBC technology (a JDBC connection pool) in the Application Server, you can define many of the characteristics of your database connections. You can create a JDBC connection pool in one of these ways:
For a complete description of JDBC connection pool features, see the Sun Java System Application Server 9.1 Administration Guide Testing a JDBC Connection PoolYou can test a JDBC connection pool for usability in one of these ways:
Both these commands fail and display an error message unless they successfully connect to the connection pool. For information about how to tune a connection pool, see the Sun Java System Application Server 9.1 Performance Tuning Guide. Creating a JDBC ResourceA JDBC resource, also called a data source, lets you make connections to a database using getConnection(). Create a JDBC resource in one of these ways:
Creating Applications That Use the JDBC APIAn application that uses the JDBC API is an application that looks up and connects to one or more databases. This section covers these topics: Sharing ConnectionsWhen multiple connections acquired by an application use the same JDBC resource, the connection pool provides connection sharing within the same transaction scope. For example, suppose Bean A starts a transaction and obtains a connection, then calls a method in Bean B. If Bean B acquires a connection to the same JDBC resource with the same sign-on information, and if Bean A completes the transaction, the connection can be shared. Connections obtained through a resource are shared only if the resource reference declared by the Java EE component allows it to be shareable. This is specified in a component’s deployment descriptor by setting the res-sharing-scope element to Shareable for the particular resource reference. To turn off connection sharing, set res-sharing-scope to Unshareable. For general information about connections and JDBC URLs, see Chapter 3, JDBC Resources, in Sun Java System Application Server 9.1 Administration Guide. Obtaining a Physical Connection From a Wrapped ConnectionThe DataSource implementation in the Application Server provides a getConnection method that retrieves the JDBC driver’s SQLConnection from the Application Server’s Connection wrapper. The method signature is as follows: public java.sql.Connection getConnection(java.sql.Connection con) throws java.sql.SQLException For example: InitialContext ctx = new InitialContext();
com.sun.appserv.jdbc.DataSource ds = (com.sun.appserv.jdbc.DataSource)
ctx.lookup("jdbc/MyBase");
Connection con = ds.getConnection();
Connection drivercon = ds.getConnection(con);
// Do db operations.
// Do not close driver connection.
con.close(); // return wrapped connection to pool.
Marking Bad ConnectionsThe DataSource implementation in the Application Server provides a markConnectionAsBad method. A marked bad connection is removed from its connection pool when it is closed. The method signature is as follows: public void markConnectionAsBad(java.sql.Connection con) For example: com.sun.appserv.jdbc.DataSource ds=
(com.sun.appserv.jdbc.DataSource)context.lookup("dataSource");
Connection con = ds.getConnection();
Statement stmt = null;
try{
stmt = con.createStatement();
stmt.executeUpdate("Update");
}
catch (BadConnectionException e){
dataSource.markConnectionAsBad(con) //marking it as bad for removal
}
finally{
stmt.close();
con.close(); //Connection will be destroyed during close.
}
Using Non-Transactional ConnectionsYou can specify a non-transactional database connection in any of these ways:
Typically, a connection is enlisted in the context of the transaction in which a getConnection call is invoked. However, a non-transactional connection is not enlisted in a transaction context even if a transaction is in progress. The main advantage of using non-transactional connections is that the overhead incurred in enlisting and delisting connections in transaction contexts is avoided. However, use such connections carefully. For example, if a non-transactional connection is used to query the database while a transaction is in progress that modifies the database, the query retrieves the unmodified data in the database. This is because the in-progress transaction hasn’t committed. For another example, if a non-transactional connection modifies the database and a transaction that is running simultaneously rolls back, the changes made by the non-transactional connection are not rolled back. Here is a typical use case for a non-transactional connection: a component that is updating a database in a transaction context spanning over several iterations of a loop can refresh cached data by using a non-transactional connection to read data before the transaction commits. Using JDBC Transaction Isolation LevelsFor general information about transactions, see Chapter 16, Using the Transaction Service and Chapter 12, Transactions, in Sun Java System Application Server 9.1 Administration Guide. For information about last agent optimization, which can improve performance, see Transaction Scope. Not all database vendors support all transaction isolation levels available in the JDBC API. The Application Server permits specifying any isolation level your database supports. The following table defines transaction isolation levels. Table 15–1 Transaction Isolation Levels
Note that you cannot call setTransactionIsolation() during a transaction. You can set the default transaction isolation level for a JDBC connection pool. For details, see Creating a Connection Pool. To verify that a level is supported by your database management system, test your database programmatically using the supportsTransactionIsolationLevel() method in java.sql.DatabaseMetaData, as shown in the following example: InitialContext ctx = new InitialContext();
DataSource ds = (DataSource)
ctx.lookup("jdbc/MyBase");
Connection con = ds.getConnection();
DatabaseMetaData dbmd = con.getMetaData();
if (dbmd.supportsTransactionIsolationLevel(TRANSACTION_SERIALIZABLE)
{ Connection.setTransactionIsolation(TRANSACTION_SERIALIZABLE); }
For more information about these isolation levels and what they mean, see the JDBC API specification. Note – Applications that change the isolation level on a pooled connection programmatically risk polluting the pool, which can lead to errors. Allowing Non-Component CallersYou can allow non-Java-EE components, such as servlet filters, lifecycle modules, and third party persistence managers, to use this JDBC connection pool. The returned connection is automatically enlisted with the transaction context obtained from the transaction manager. Standard Java EE components can also use such pools. Connections obtained by non-component callers are not automatically closed at the end of a transaction by the container. They must be explicitly closed by the caller. You can enable non-component callers in the following ways:
Restrictions and OptimizationsThis section discusses restrictions and performance optimizations that affect using the JDBC API. Disabling Stored Procedure Creation on SybaseBy default, DataDirect and Sun Java System JDBC drivers for Sybase databases create a stored procedure for each parameterized PreparedStatement. On the Application Server, exceptions are thrown when primary key identity generation is attempted. To disable the creation of these stored procedures, set the property PrepareMethod=direct. Chapter 16 Using the Transaction ServiceThe Java EE platform provides several abstractions that simplify development of dependable transaction processing for applications. This chapter discusses Java EE transactions and transaction support in the Sun Java System Application Server. This chapter contains the following sections: For more information about the JavaTM Transaction API (JTA) and Java Transaction Service (JTS), see Chapter 12, Transactions, in Sun Java System Application Server 9.1 Administration Guide and the following sites: http://java.sun.com/products/jta/ and http://java.sun.com/products/jts/. You might also want to read “Chapter 35: Transactions” in the Java EE 5 Tutorial. Transaction Resource ManagersThere are three types of transaction resource managers:
For details about how transaction resource managers, the transaction service, and applications interact, see Chapter 12, Transactions, in Sun Java System Application Server 9.1 Administration Guide. Transaction ScopeA local transaction involves only one non-XA resource and requires that all participating application components execute within one process. Local transaction optimization is specific to the resource manager and is transparent to the Java EE application. In the Application Server, a JDBC resource is non-XA if it meets any of the following criteria:
A transaction remains local if the following conditions remain true:
Transactions that involve multiple resources or multiple participant processes are distributed or global transactions. A global transaction can involve one non-XA resource if last agent optimization is enabled. Otherwise, all resourced must be XA. The use-last-agent-optimization property is set to true by default. For details about how to set this property, see Configuring the Transaction Service. If only one XA resource is used in a transaction, one-phase commit occurs, otherwise the transaction is coordinated with a two-phase commit protocol. A two-phase commit protocol between the transaction manager and all the resources enlisted for a transaction ensures that either all the resource managers commit the transaction or they all abort. When the application requests the commitment of a transaction, the transaction manager issues a PREPARE_TO_COMMIT request to all the resource managers involved. Each of these resources can in turn send a reply indicating whether it is ready for commit (PREPARED) or not (NO). Only when all the resource managers are ready for a commit does the transaction manager issue a commit request (COMMIT) to all the resource managers. Otherwise, the transaction manager issues a rollback request (ABORT) and the transaction is rolled back. Distributed Transaction RecoveryNote – Some topics in the documentation pertain to features that are available only in domains that are configured to support clusters. Examples of domains that support clusters are domains that are created with the cluster profile or the enterprise profile. For information about profiles, see Usage Profiles in Sun Java System Application Server 9.1 Administration Guide. To enable cluster-wide automatic recovery, you must first facilitate storing of transaction logs in a shared file system. You can do this in one of these ways:
Next, you must set the transaction service's delegated-recovery property to true (the default is false). For information about setting tx-log-dir and delegated-recovery, see Configuring the Transaction Service. For information about setting log-root and other general logging settings, see Chapter 17, Configuring Logging, in Sun Java System Application Server 9.1 Administration Guide. For information about system-property and the domain.xml file, see the Sun Java System Application Server 9.1 Administration Reference. Configuring the Transaction ServiceYou can configure the transaction service in the Application Server in the following ways:
The Transaction Manager, the Transaction Synchronization Registry, and UserTransactionYou can access the Application Server transaction manager, a javax.transaction.TransactionManager implementation, using the JNDI subcontext java:comp/TransactionManager or java:appserver/TransactionManager. You can access the Application Server transaction synchronization registry, a javax.transaction.TransactionSynchronizationRegistry implementation, using the JNDI subcontext java:comp/TransactionSynchronizationRegistry or java:appserver/TransactionSynchronizationRegistry. You can also request injection of a TransactionManager or TransactionSynchronizationRegistry object using the @Resource annotation. Accessing the transaction synchronization registry is recommended. For details, see Java Specification Request (JSR) 907. You can also access java:comp/UserTransaction. Transaction LoggingThe transaction service writes transactional activity into transaction logs so that transactions can be recovered. You can control transaction logging in these ways:
Storing Transaction Logs in a DatabaseFor multi-core machines, logging transactions to a database may be more efficient. To log transactions to a database, follow these steps:
For information about JDBC connection pools and resources, see Chapter 15, Using the JDBC API for Database Access. For more information about the asadmin create-jvm-options command, see the Sun Java System Application Server 9.1 Reference Manual. Table 16–1 Schema for txn_log_table
The size of the SERVERNAME column should be at least the length of the Application Server host name plus 10 characters. The size of the GTRID column should be at least 64 bytes. To define the SQL used by the transaction manager when it is storing its transaction logs in the database, use the following flags: -Dcom.sun.jts.dblogging.insertquery=sql statement -Dcom.sun.jts.dblogging.deletequery=sql statement The default statements are as follows: -Dcom.sun.jts.dblogging.insertquery=insert into txn_log_table values ( ?, ? , ? ) -Dcom.sun.jts.dblogging.deletequery=delete from txn_log_table where localtid = ? and servername = ? To set one of these flags using the asadmin create-jvm-options command, you must quote the statement. For example: create-jvm-options '-Dcom.sun.jts.dblogging.deletequery=delete from txn_log_table where gtrid = ?' You can also set JVM options in the Admin Console. In the developer profile, select the Application Server component and the JVM Settings tab. In the cluster profile, select the JVM Settings component under the relevant configuration. These flags and their statements must also be quoted in the Admin Console. For example: '-Dcom.sun.jts.dblogging.deletequery=delete from txn_log_table where gtrid = ?' Recovery WorkaroundsThe Application Server provides workarounds for some known issues with the recovery implementations of the following JDBC drivers. These workarounds are used unless explicitly disabled. In the Oracle thin driver, the XAResource.recover method repeatedly returns the same set of in-doubt Xids regardless of the input flag. According to the XA specifications, the Transaction Manager initially calls this method with TMSTARTSCAN and then with TMNOFLAGS repeatedly until no Xids are returned. The XAResource.commit method also has some issues. To disable the Application Server workaround, set the oracle-xa-recovery-workaround property value to false. For details about how to set this property, see Configuring the Transaction Service. Note – These workarounds do not imply support for any particular JDBC driver. Chapter 17 Using the Java Naming and Directory InterfaceA naming service maintains a set of bindings, which relate names to objects. The Java EE naming service is based on the Java Naming and Directory InterfaceTM (JNDI) API. The JNDI API allows application components and clients to look up distributed resources, services, and EJB components. For general information about the JNDI API, see http://java.sun.com/products/jndi/. You can also see the JNDI tutorial at http://java.sun.com/products/jndi/tutorial/. This chapter contains the following sections: Accessing the Naming ContextThe Application Server provides a naming environment, or context, which is compliant with standard Java EE requirements. A Context object provides the methods for binding names to objects, unbinding names from objects, renaming objects, and listing the bindings. The InitialContext is the handle to the Java EE naming service that application components and clients use for lookups. The JNDI API also provides subcontext functionality. Much like a directory in a file system, a subcontext is a context within a context. This hierarchical structure permits better organization of information. For naming services that support subcontexts, the Context class also provides methods for creating and destroying subcontexts. The rest of this section covers these topics: Note – Each resource within a server instance must have a unique name. However, two resources in different server instances or different domains can have the same name. Global JNDI NamesGlobal JNDI names are assigned according to the following precedence rules:
Accessing EJB Components Using the CosNaming Naming ContextThe preferred way of accessing the naming service, even in code that runs outside of a Java EE container, is to use the no-argument InitialContext constructor. However, if EJB client code explicitly instantiates an InitialContext that points to the CosNaming naming service, it is necessary to set the java.naming.factory.initial property to com.sun.jndi.cosnaming.CNCtxFactory in the client JVM when accessing EJB components. You can set this property as a command-line argument, as follows:
Or you can set this property in the code, as follows: Properties properties = null;
try {
properties = new Properties();
properties.put("java.naming.factory.initial",
"com.sun.jndi.cosnaming.CNCtxFactory");
...
The java.naming.factory.initial property applies to only one instance; it is not cluster-aware. Accessing EJB Components in a Remote Application ServerThe recommended approach for looking up an EJB component in a remote Application Server from a client that is a servlet or EJB component is to use the Interoperable Naming Service syntax. Host and port information is prepended to any global JNDI names and is automatically resolved during the lookup. The syntax for an interoperable global name is as follows: corbaname:iiop:host:port#a/b/name This makes the programming model for accessing EJB components in another Application Server exactly the same as accessing them in the same server. The deployer can change the way the EJB components are physically distributed without having to change the code. For Java EE components, the code still performs a java:comp/env lookup on an EJB reference. The only difference is that the deployer maps the ejb-reference element to an interoperable name in an Application Server deployment descriptor file instead of to a simple global JNDI name. For example, suppose a servlet looks up an EJB reference using java:comp/env/ejb/Foo, and the target EJB component has a global JNDI name of a/b/Foo. The ejb-ref element in sun-web.xml looks like this: <ejb-ref> <ejb-ref-name>ejb/Foo</ejb-ref-name> <jndi-name>corbaname:iiop:host:port#a/b/Foo</jndi-name> <ejb-ref> The code looks like this: Context ic = new InitialContext();
Object o = ic.lookup("java:comp/env/ejb/Foo");
For a client that doesn’t run within a Java EE container, the code just uses the interoperable global name instead of the simple global JNDI name. For example: Context ic = new InitialContext();
Object o = ic.lookup("corbaname:iiop:host:port#a/b/Foo");
Objects stored in the interoperable naming context and component-specific (java:comp/env) naming contexts are transient. On each server startup or application reloading, all relevant objects are re-bound to the namespace. Naming Environment for Lifecycle ModulesLifecycle listener modules provide a means of running short or long duration tasks based on Java technology within the application server environment, such as instantiation of singletons or RMI servers. These modules are automatically initiated at server startup and are notified at various phases of the server life cycle. For details about lifecycle modules, see Chapter 13, Developing Lifecycle Listeners. The configured properties for a lifecycle module are passed as properties during server initialization (the INIT_EVENT). The initial JNDI naming context is not available until server initialization is complete. A lifecycle module can get the InitialContext for lookups using the method LifecycleEventContext.getInitialContext() during, and only during, the STARTUP_EVENT, READY_EVENT, or SHUTDOWN_EVENT server life cycle events. Configuring ResourcesThe Application Server exposes the following special resources in the naming environment. Full administration details are provided in the following sections: External JNDI ResourcesAn external JNDI resource defines custom JNDI contexts and implements the javax.naming.spi.InitialContextFactory interface. There is no specific JNDI parent context for external JNDI resources, except for the standard java:comp/env/. Create an external JNDI resource in one of these ways:
Custom ResourcesA custom resource specifies a custom server-wide resource object factory that implements the javax.naming.spi.ObjectFactory interface. There is no specific JNDI parent context for external JNDI resources, except for the standard java:comp/env/. Create a custom resource in one of these ways:
Using a Custom jndi.properties FileTo use a custom jndi.properties file, specify the path to the file in one of the following ways:
This adds the jndi.properties file to the Shared Chain class loader. For more information about class loading, see Chapter 2, Class Loaders. For each property found in more than one jndi.properties file, the Java EE naming service either uses the first value found or concatenates all of the values, whichever makes sense. Mapping ReferencesThe following XML elements in the Application Server deployment descriptors map resource references in application client, EJB, and web application components to JNDI names configured in the Application Server:
These elements are part of the sun-web.xml, sun-ejb-ref.xml, and sun-application-client.xml deployment descriptor files. For more information about how these elements behave in each of the deployment descriptor files, see Appendix A, Deployment Descriptor Files, in Sun Java System Application Server 9.1 Application Deployment Guide. The rest of this section uses an example of a JDBC resource lookup to describe how to reference resource factories. The same principle is applicable to all resources (such as JMS destinations, JavaMail sessions, and so on). The @Resource annotation in the application code looks like this: @Resource(name="jdbc/helloDbDs") javax.sql.DataSource ds; This references a resource with the JNDI name of java:comp/env/jdbc/helloDbDs. If this is the JNDI name of the JDBC resource configured in the Application Server, the annotation alone is enough to reference the resource. However, you can use an Application Server specific deployment descriptor to override the annotation. For example, the resource-ref element in the sun-web.xml file maps the res-ref-name (the name specified in the annotation) to the JNDI name of another JDBC resource configured in the Application Server. <resource-ref> <res-ref-name>jdbc/helloDbDs</res-ref-name> <jndi-name>jdbc/helloDbDataSource</jndi-name> </resource-ref> Chapter 18 Using the Java Message ServiceThis chapter describes how to use the JavaTM Message Service (JMS) API. The Sun Java System Application Server has a fully integrated JMS provider: the Sun Java System Message Queue software. For general information about the JMS API, see “Chapter 33: The Java Message Service API” in the Java EE 5 Tutorial. For detailed information about JMS concepts and JMS support in the Application Server, see Chapter 4, Configuring Java Message Service Resources, in Sun Java System Application Server 9.1 Administration Guide. This chapter contains the following sections: The JMS ProviderThe Application Server support for JMS messaging, in general, and for message-driven beans, in particular, requires messaging middleware that implements the JMS specification: a JMS provider. The Application Server uses the Sun Java System Message Queue software as its native JMS provider. The Message Queue software is tightly integrated into theApplication Server, providing transparent JMS messaging support. This support is known within Application Server as the JMS Service. The JMS Service requires only minimal administration. The relationship of the Message Queue software to the Application Server can be one of these types: EMBEDDED, LOCAL, or REMOTE. The effects of these choices on the Message Queue broker life cycle are as follows:
For more information about setting the type and the default JMS host, see Configuring the JMS Service. For more information about the Message Queue software, refer to the documentation at http://docs.sun.com/coll/1343.4. For general information about the JMS API, see the JMS web page at http://java.sun.com/products/jms/index.html. Note – Some topics in the documentation pertain to features that are available only in domains that are configured to support clusters. Examples of domains that support clusters are domains that are created with the cluster profile or the enterprise profile. For information about profiles, see Usage Profiles in Sun Java System Application Server 9.1 Administration Guide. Message Queue Resource AdapterThe Sun Java System Message Queue software is integrated into the Application Server using a resource adapter that is compliant with the Connector specification. The module name of this system resource adapter is jmsra. Every JMS resource is converted to a corresponding connector resource of this resource adapter as follows:
You use connector configuration tools to manage JMS resources. For more information, see Chapter 12, Developing Connectors. Generic Resource AdapterThe Application Server provides a generic resource adapter for JMS, for those who want to use a JMS provider other than Sun Java System Message Queue. For details, see http://genericjmsra.dev.java.net/ and Configuring the Generic Resource Adapter for JMS in Sun Java System Application Server 9.1 Administration Guide. Administration of the JMS ServiceTo configure the JMS Service and prepare JMS resources for use in applications deployed to the Application Server, you must perform these tasks: For more information about JMS administration tasks, see Chapter 4, Configuring Java Message Service Resources, in Sun Java System Application Server 9.1 Administration Guide and the Sun Java System Message Queue 4.1 Administration Guide. Configuring the JMS ServiceThe JMS Service configuration is available to all inbound and outbound connections pertaining to the Application Server cluster or instance. You can edit the JMS Service configuration in the following ways:
You can override the JMS Service configuration using JMS connection factory settings. For details, see Chapter 4, Configuring Java Message Service Resources, in Sun Java System Application Server 9.1 Administration Guide. Note – The Application Server instance must be restarted after configuration of the JMS Service. The Default JMS HostA JMS host refers to a Sun Java System Message Queue broker. A default JMS host for the JMS service is provided, named default_JMS_host. This is the JMS host that the Application Server uses for performing all Message Queue broker administrative operations, such as creating and deleting JMS destinations. If you have created a multi-broker cluster in the Message Queue software, delete the default JMS host, then add the Message Queue cluster’s brokers as JMS hosts. In this case, the default JMS host becomes the first JMS host in the AddressList. For more information about the AddressList, see JMS Connection Features. You can also explicitly set the default JMS host; see Configuring the JMS Service. When the Application Server uses a Message Queue cluster, it executes Message Queue specific commands on the default JMS host. For example, when a physical destination is created for a Message Queue cluster of three brokers, the command to create the physical destination is executed on the default JMS host, but the physical destination is used by all three brokers in the cluster. Creating JMS HostsYou can create additional JMS hosts in the following ways:
For machines having more than one host, use the Host field in the Admin Console or the -–mqhost option of create-jms-host to specify the address to which the broker binds. Checking Whether the JMS Provider Is RunningYou can use the asadmin jms-ping command to check whether a Sun Java System Message Queue instance is running. For details, see the Sun Java System Application Server 9.1 Reference Manual. Creating Physical DestinationsProduced messages are delivered for routing and subsequent delivery to consumers using physical destinations in the JMS provider. A physical destination is identified and encapsulated by an administered object (a Topic or Queue destination resource) that an application component uses to specify the destination of messages it is producing and the source of messages it is consuming. If a message-driven bean is deployed and the Queuephysical destination it listens to doesn’t exist, the Application Server automatically creates the physical destination and sets the value of the property maxNumActiveConsumers to -1 (see Load-Balanced Message Inflow). However, it is good practice to create the Queue physical destination beforehand. You can create a JMS physical destination in the following ways:
To purge all messages currently queued at a physical destination, use the asadmin flush-jmsdest command. This deletes the messages before they reach any message consumers. For details, see the Sun Java System Application Server 9.1 Reference Manual. To create a destination resource, see Creating JMS Resources: Destinations and Connection Factories. Creating JMS Resources: Destinations and Connection FactoriesYou can create two kinds of JMS resources in the Application Server:
In either case, the steps for creating a JMS resource are the same. You can create a JMS resource in the following ways:
Note – All JMS resource properties that used to work with version 7 of the Application Server are supported for backward compatibility. Restarting the JMS Client After JMS ConfigurationWhen a JMS client accesses a JMS administered object for the first time, the client JVM retrieves the JMS service configuration from the Application Server. Further changes to the configuration are not available to the client JVM until the client is restarted. JMS Connection FeaturesThe Sun Java System Message Queue software supports the following JMS connection features: Both these features use the AddressList configuration, which is populated with the hosts and ports of the JMS hosts defined in the Application Server. The AddressList is updated whenever a JMS host configuration changes. The AddressList is inherited by any JMS resource when it is created and by any MDB when it is deployed. Note – In the Sun Java System Message Queue software, the AddressList property is called imqAddressList. Connection PoolingThe Application Server pools JMS connections automatically. To dynamically modify connection pool properties using the Admin Console, go to either the Connection Factories page (see Creating JMS Resources: Destinations and Connection Factories) or the Connector Connection Pools page (see Deploying and Configuring a Stand-Alone Connector Module). To use the command line, use the asadmin create-connector-connection-pool command to manage the pool (see Deploying and Configuring a Stand-Alone Connector Module. For the developer profile, the addresslist-behavior JMS service attribute is set to random by default. This means that each ManagedConnection (physical connection) created from the ManagedConnectionFactory selects its primary broker in a random way from the AddressList. For the cluster and enterprise profiles, the addresslist-behavior JMS service attribute is set to priority by default. This means that the first broker in the AddressList is selected first. This first broker is the local colocated Message Queue broker. If this broker is unavailable, connection attempts are made to brokers in the order in which they are listed in the AddressList. This ensures colocated production and consumption of messages and equitable load distribution across the Message Queue broker cluster. When a JMS connection pool is created, there is one ManagedConnectionFactory instance associated with it. If you configure the AddressList as a ManagedConnectionFactory property, the AddressList configuration in the ManagedConnectionFactory takes precedence over the one defined in the Application Server. Connection FailoverTo specify whether the Application Server tries to reconnect to the primary broker if the connection is lost, set the reconnect-enabled attribute in the JMS service. To specify the number of retries and the time between retries, set the reconnect-attempts and reconnect-interval-in-seconds attributes, respectively. If reconnection is enabled and the primary broker goes down, the Application Server tries to reconnect to another broker in the AddressList. The AddressList is updated whenever a JMS host configuration changes. The logic for scanning is decided by two JMS service attributes, addresslist-behavior and addresslist-iterations. You can override these settings using JMS connection factory settings. For details, see Chapter 4, Configuring Java Message Service Resources, in Sun Java System Application Server 9.1 Administration Guide. The Sun Java System Message Queue software transparently transfers the load to another broker when the failover occurs. JMS semantics are maintained during failover. Load-Balanced Message InflowYou can configure ActivationSpec properties of the jmsra resource adapter in the sun-ejb-jar.xml file for a message-driven bean using activation-config-property elements. Whenever a message-driven bean (EndPointFactory) is deployed, the connector runtime engine finds these properties and configures them accordingly in the resource adapter. See activation-config-property in Sun Java System Application Server 9.1 Application Deployment Guide. The Application Server transparently enables messages to be delivered in random fashion to message-driven beans having same ClientID. The ClientID is required for durable subscribers. For nondurable subscribers in which the ClientID is not configured, all instances of a specific message-driven bean that subscribe to same topic are considered equal. When a message-driven bean is deployed to multiple instances of the Application Server, only one of the message-driven beans receives the message. If multiple distinct message-driven beans subscribe to same topic, one instance of each message-driven bean receives a copy of the message. To support multiple consumers using the same queue, set the maxNumActiveConsumers property of the physical destination to a large value. If this property is set, the Sun Java System Message Queue software allows multiple message-driven beans to consume messages from same queue. The message is delivered randomly to the message-driven beans. If maxNumActiveConsumers is set to -1, there is no limit to the number of consumers. To ensure that local delivery is preferred, set addresslist-behavior to priority. This setting specifies that the first broker in the AddressList is selected first. This first broker is the local colocated Message Queue instance. If this broker is unavailable, connection attempts are made to brokers in the order in which they are listed in the AddressList. This setting is the default for Application Server instances that belong to a cluster. Note – Some topics in the documentation pertain to features that are available only in domains that are configured to support clusters. Examples of domains that support clusters are domains that are created with the cluster profile or the enterprise profile. For information about profiles, see Usage Profiles in Sun Java System Application Server 9.1 Administration Guide. JMS Service High AvailabilityThere are two levels of availability for JMS components:
You can enable data availability in the Sun Java System Message Queue cluster that comprises the Java Message Service (JMS). Messages are saved to the high-availability database (HADB) if HADB is installed, data availability is enabled, and the enterprise profile is selected. For information about profiles, see Usage Profiles in Sun Java System Application Server 9.1 Administration Guide. You must enable availability for the Application Server instances before you can enable data availability for the corresponding brokers. Note – Individual applications and modules cannot control or override JMS availability. To enable data availability, select the Availability Service component under the relevant configuration in the Admin Console. Check the Availability Service box. To enable availability for the JMS service, select the JMS Availability tab, then check the Availability Service box. All instances in an Application Server cluster should have the same instance availability and JMS availability settings to ensure consistent behavior. For details, see the Sun Java System Application Server 9.1 High Availability Administration Guide. Note – Some topics in the documentation pertain to features that are available only in domains that are configured to support clusters. Examples of domains that support clusters are domains that are created with the cluster profile or the enterprise profile. For information about profiles, see Usage Profiles in Sun Java System Application Server 9.1 Administration Guide. Transactions and Non-Persistent MessagesDuring transaction recovery, non-persistent messages might be lost. If the broker fails between the transaction manager’s prepare and commit operations, any non-persistent message in the transaction is lost and cannot be delivered. A message that is not saved to a persistent store is not available for transaction recovery. Authentication With ConnectionFactoryIf your web, EJB, or client module has res-auth set to Container, but you use the ConnectionFactory.createConnection("user","password") method to get a connection, the Application Server searches the container for authentication information before using the supplied user and password. Version 7 of the Application Server threw an exception in this situation. Message Queue varhome DirectoryThe Sun Java System Message Queue software uses a default directory for storing data such as persistent messages and its log file. This directory is called varhome. The Application Server uses domain-dir/imq as the varhome directory if the type of relationship between the Application Server and the Message Queue software is LOCAL or EMBEDDED. If the relationship type is REMOTE, the Message Queue software determines the varhome location. For more information about the types of relationships between the Application Server and Message Queue, see The JMS Provider. When executing Message Queue scripts such as as-install/imq/bin/imqusermgr, use the -varhome option to point the scripts to the Message Queue data if the relationship type is LOCAL or EMBEDDED. For example: imqusermgr -varhome $AS_INSTALL/domains/domain1/imq add -u testuser For more information about the Message Queue software, refer to the documentation at http://docs.sun.com/coll/1343.4. Delivering SOAP Messages Using the JMS APIWeb service clients use the Simple Object Access Protocol (SOAP) to communicate with web services. SOAP uses a combination of XML-based data structuring and Hyper Text Transfer Protocol (HTTP) to define a standardized way of invoking methods in objects distributed in diverse operating environments across the Internet. For more information about SOAP, see the Apache SOAP web site at http://xml.apache.org/soap/index.html. You can take advantage of the JMS provider’s reliable messaging when delivering SOAP messages. You can convert a SOAP message into a JMS message, send the JMS message, then convert the JMS message back into a SOAP message. The following sections explain how to do these conversions:
|
|||||||||||||||||||||