WorkManager

WebLogic WorkManager with EJB3 And MaxThread Constraint

Hi,
Jay SenSharma

Jay SenSharma

WebLogic Provides us a feature to manage the WebLogic Threads per application using WorkManagers. In this demo we will see how we can instruct WebLogic to allocate only one thread to process the Clients request. We will develop a simple EJB3 application and we will assign a WorkManager with MaxThreadConstraint as 2. It means for Any number of Clients request to that EJB, the WebLogic will allocate only 1 Thread for request processing.
.
Step1). Please follow the instructions mentioned in the  link: http://middlewaremagic.com/weblogic/?p=2691 to create WebLogic WorkManager in seconds using WLST. Just make sure that you chose the following values for Max and Min Threads to see how this sample works. Later you can use your own values.
MaxThread=2
MinThread=2
.
Step2). Now create a Directory somewhere in your file system like:  “C:tempEJB3_With_WorkManager”
.
Step3). Now create a EJB remote Interface “CalculatorRemote.java” inside “C:tempEJB3_With_WorkManager” like following:
//CalculatorRemote.java
package calculator;
import javax.ejb.*;
@Remote
public interface CalculatorRemote
{
  public int add(int x,int y);
}
Step4). Now ssame way create a Stateless Session Bean “CalculatorBean.java” inside “C:tempEJB3_With_WorkManager” like following:
//CalculatorBean.java
package calculator;
import javax.ejb.*;
@Stateless
public class CalculatorBean implements CalculatorRemote
 {
   public int add(int x,int y)
    {
	  System.out.println("Current ThreadName Is: "+Thread.currentThread().getName());
      return (x+y);
    }
 }
Step5). Now create a directory with name “META-INF” inside “C:tempEJB3_With_WorkManager” and then create a file “weblogic-ejb-jar.xml”  inside “C:tempEJB3_With_WorkManagerMETA-INF”  directory like following so that we can assign the WebLogic WorkManager to the EJB using “dispatch-policy” tag:
<?xml version='1.0' encoding='UTF-8'?>
<weblogic-ejb-jar xmlns="http://www.bea.com/ns/weblogic/10.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <weblogic-enterprise-bean>
    <ejb-name>CalculatorBean</ejb-name>
    <stateless-session-descriptor>
      <pool></pool>
      <stateless-clustering>
        <home-is-clusterable>false</home-is-clusterable>
        <stateless-bean-is-clusterable>false</stateless-bean-is-clusterable>
      </stateless-clustering>
    </stateless-session-descriptor>
    <transaction-descriptor></transaction-descriptor>
    <jndi-name>X</jndi-name>
    <dispatch-policy>JackWorkManager</dispatch-policy>
    <remote-client-timeout>0</remote-client-timeout>
  </weblogic-enterprise-bean>
</weblogic-ejb-jar>
Step6). Now run the “setWLSEnv.cmd” in a command prompt to set the classpath then Compile and EJBs and then make a Jar of it like following:
compiling_Ejb3

compiling_Ejb3

Step7). Now deploy the above created EJB3 jar file “Ejb3.jar” in WebLogic Server.
.
Step8). Check the AdminConsole where you are able to see the WorkManager properly assigned to your EJB3 or Not?
 EJB3_Workmanager_Console_look

EJB3_Workmanager_Console_look

Step9). Now Create a Client somewhere in your file system and set the Classpath to Ejb3.jar which we created above…. Client program like following “Ejb3Client.java”.  This client is going to send 5000 fresh requests to the WebLogic Server.
package calculator;
import javax.naming.*;
import java.util.*;
public class  Ejb3Client
{
	public final static String JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory";
	private static String serverUrl ="t3://localhost:7001";
	public static void main(String[] ar)  throws Exception
	{
		for(int i=0;i<=5000;i++)
		 {
           InitialContext ic=null;
           try{
		        Hashtable env = new Hashtable();
		        env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
		        env.put(Context.PROVIDER_URL, serverUrl);
  		        ic = new InitialContext(env);
              }
            catch(Exception e)
             {
			    System.out.println("nt Didnot get InitialContext: "+e);
			 }
           try
             {

                Object obj=ic.lookup("calc#calculator.CalculatorRemote");
                CalculatorRemote remote=(CalculatorRemote)obj;
                System.out.println("nntRemote=>"+remote.getClass());

				System.out.println("nntClassLoading=>1");
                Class.forName("calculator.CalculatorRemote");
				System.out.println("nntClassLoading=>2");

                System.out.println("nnt SUM = "+remote.add(Integer.parseInt(ar[0]),Integer.parseInt(ar[1])));
             }
           catch(Exception e)
             {
                System.out.println("nnt jack Exception => "+e);
                e.printStackTrace();
             }
           System.out.println("nt Iteration ------------ "+i);
	    }
	}
}

Step10). Run the client and then check the Server STDOUT that all the 5000 request will be processed only by a Two Execute Thread….It means due to MaxThreadConstraint=2 the WebLogic will not allocate more than two thread to process clients request.
EJB3_Workmanager_Client_Console_Output

EJB3_Workmanager_Client_Console_Output

In the output (STDOUT) of the Server you will see that there are only 2 Threads which are processing all the 5000 Clients request…..

Current ThreadName Is: [ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'
.
.
Thanks
Jay SenSharma

Creating WorkManager Using WLST

Hi,

Jay SenSharma

Jay SenSharma

Here we are going to see a very Simple WLST Script to configure the WorkManager with MaxThreadConstraint and MinThreadConstraint and Assigning them to the WorkManager which we created using the same Script.

Step1). Create a Directry some where in your File System like: “C:WorkManager_WLST”

Step2). Write a Property file with the name “workManagerProperties.properties” inside the “C:WorkManager_WLST”

adminServerName=AdminServer
ServerName=AdminServer
domainName=base_domain
domainDire=C:/bea103/user_projects/domains/base_domain
host=localhost
protocol=t3
AdminPort=7001
username=weblogic
password=weblogic
MinThread=7
MaxThread=15
workManagerName=MyTestWorkManager
maxThreadConstraintName=MyTestMaxThreadConstraint
minThreadConstraintName=MyTestMinThreadConstraint

Step3). Now write the WLST pythin script “createWorkManager.py” inside “”C:WorkManager_WLST”” to create the WorkManager like following

import sys
import os
import jarray
import dircache
from java.io import File
from java.lang import String

myPropertyFile = "workManagerProperties.properties"

#=======================================================================================
# connection() Definition
#=======================================================================================
def connection():
	print '===> Connecting as '+ username + ' To WebLogic URL ' + url + '...'
	try:
		connect(username, password, url)
	except WLSTException:
		print '==> Error Connecting to The URL ' + url
		CancelEdit('y')
		exit()

print '==== Exiting Because Of Connectivity Error ===='
#=======================================================================================
print '======= Reading Property File and Connecting to Server ========'
loadProperties(myPropertyFile)
url=protocol + '://' + host + ':' + AdminPort
connection()

edit()
startEdit()
print '======= Creating a WorkManager name as ======='
cd('edit:/SelfTuning/' + domainName + '/WorkManagers/')
create(workManagerName,'WorkManagers')
cd('edit:/SelfTuning/' + domainName + '/WorkManagers/' + workManagerName)
cmo.addTarget(getMBean("/Servers/"+ ServerName))
save()
print ' WorkManager Created...'

print '======= Creating MaxThreadsConstraint ======='
cd('edit:/SelfTuning/' + domainName + '/MaxThreadsConstraints/')
try:
	create(maxThreadConstraintName,'MaxThreadsConstraints')
except Exception:
	print 'Issue in Creating MaxThreads exiting'
cd('edit:/SelfTuning/' + domainName + '/MaxThreadsConstraints/' + maxThreadConstraintName)
cmo.addTarget(getMBean("/Servers/"+ ServerName))
set('Count',MaxThread)
save()

print '======= Creating MinThreadsConstraint ======='
cd('edit:/SelfTuning/' + domainName + '/MinThreadsConstraints/')
try:
	create(minThreadConstraintName,'MinThreadsConstraints')
except Exception:
	print 'Issue In Creating MinThreads '
cd('edit:/SelfTuning/' + domainName + '/MinThreadsConstraints/' + minThreadConstraintName)
cmo.addTarget(getMBean("/Servers/"+ ServerName))
set('Count',MinThread)
save()

print '======= Assigning the MaxThreadConstraint to the WorkManager ======='
cd('edit:/SelfTuning/' + domainName + '/WorkManagers/' + workManagerName)
bean=getMBean('/SelfTuning/' + domainName + '/MaxThreadsConstraints/' + maxThreadConstraintName)
cmo.setMaxThreadsConstraint(bean)

print '======= Assigning the MinThreadConstraint to the WorkManager ======='
cd('edit:/SelfTuning/' + domainName + '/WorkManagers/' + workManagerName)
bean=getMBean('/SelfTuning/' + domainName + '/MinThreadsConstraints/' + minThreadConstraintName)
cmo.setMinThreadsConstraint(bean)

save()
activate(block="true")
print '==> WorkManager Creation Finished ... Please Double Check from AdminConsole...'
disconnect()

Step4). Open a Command Window and then run the “setWLSEn.cmd” (for windows)… or “setWLSEnv.sh” (for Unix Based OS) Then run the WLST Script :
NOTE: Run the setWLSEnv.sh always with preseeding two DOTs like
“. ./setWLSEnv.sh”
The first DOT represents that set the Environment in the current Shell, AND the second ./ represents execute the script from the current directory.

running the setWLSEnv.cmd to set CLASSPATH/PATH

running the setWLSEnv.cmd to set CLASSPATH/PATH

java weblogic.WLST createWorkManager.py workManagerProperties.properties

Running the WLST Script to Create WorkManager

Running the WLST Script to Create WorkManager

Step5). Double check the AdminConsole that everything looks good?

Admin Console After Creation of WorkManager

Admin Console After Creation of WorkManager

.
.
Thanks
Jay SenSharma


Adding WorkManager Using Plan.xml to a WAR file

Hi,

Jay SenSharma

Jay SenSharma

Suppose if you already have deployed your WebApplication (WAR) file on the Server …this time if you hit your Application then in AdminConsole you will see that the requests are being processed by the “default” workManager.

To see this you can login to your applications workmanager status ….
AdminConsole—>Deployments—.YourWebApplication—>Monitoring (TAB)—>workload (Sub tab)
.
Here you will see that as soon as you hit your webapplication it’s request is being served by the “default” work manager. You don’t want to Change your WebApplication by adding <wl-dispatch-policy> tag inside your “weblogic.xml”. So this can be done by using “Plan.xml”…using this file we will assign WorkManager Dynamically to an existing application without physically touching the actual application.
.
NOTE: Please make sure that atleast on “weblogic.xml” is already available inside your WebApplication which uses WLS9.x onwards schema defination…like following… If you already have weblogic.xml inside your WAR then it’s good…or else please add the following empty “weblogic.xml” inside your WebApp…
<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<weblogic-web-app xmlns=”http://www.bea.com/ns/weblogic/90″>
</weblogic-web-app>

.
Step1). Create a WorkManager through AdminConsole with the following configuration:
with the following Configuration: in your “config.xml”…or define your Workmanager according to your requirement
<self-tuning>
<context-request-class>
<name>ContextReqClass-0</name>
<target>AdminServer</target>
</context-request-class>
<min-threads-constraint>
<name>MyMaxConstraint</name>
<target>AdminServer</target>
<count>1</count>
</min-threads-constraint>
<capacity>
<name>CapacityConstraint-0</name>
<target>AdminServer</target>
<count>1</count>
</capacity>
<work-manager>
<name>myConsoleWorkManager</name>
<target>AdminServer</target>
<context-request-class>ContextReqClass-0</context-request-class>
<min-threads-constraint>MyMaxConstraint</min-threads-constraint>
<capacity>CapacityConstraint-0</capacity>
</work-manager>
</self-tuning>
Note: After configuring the above workManager we need to restart the Server…As a Best practice.
.
.
Step2). Open a Command window or a Shell prompt and then run “. ./setWLSEnv.sh” or “setDomainEnv.sh” to set the environment in that shell.
.
.
Step3). In the Shell prompt Move till the your WAR file…Lets say your WAR filename is “MyWorkManagerDemo.war”. which is placed inside
“/opt/apps” directory then first do
cd /opt/apps
.
.
Step4). Now run the “weblogic.PlanGenerator” utility to generate the Plan.xml file in the current Directory. Like following:
java weblogic.PlanGenerator -all MyWorkManagerDemo.war
OUTPUT:
Generating plan for application MyWorkManagerDemo.war
Export option is: all
Exporting properties…
Saving plan to /opt/apps/plan.xml…
<Mar 14, 2010 2:57:00 PM IST> <Info> <J2EE Deployment SPI> <BEA-260072> <Saved configuration for application, MyWorkManagerDemo>
.
.
Step5). Now the generated “plan.xml” file will be bit large …we need to edit it…
.
.
Step6). Edit it like:
You will find <variable-definition> with many sub tags like <variable>   Just edit one of them and delete rest of the <variable> Tags
you can give any name to the variable like “firstVariableName”.
Now edit the next line <value xsi:nil=”true”></value>  by removing the  xsi:nil=”true” from this Tag….means you need to change it to and then add your WorkManager name there like:
<value>myConsoleWorkManager</value>
Now edit the Module which you want to override: <module-override> and then assign the Variable there and <config-root> tag pointing to the Plan.xml directory…Finally you will get a “plan.xml” file like following:
<?xml version='1.0' encoding='UTF-8'?>
<deployment-plan xmlns="http://www.bea.com/ns/weblogic/deployment-plan" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/deployment-plan http://www.bea.com/ns/weblogic/deployment-plan/1.0/deployment-plan.xsd" global-variables="false">
<application-name>MyWorkManagerDemo.war</application-name>
<variable-definition>
<variable>
<name>firstVariableName</name>
<value>myConsoleWorkManager</value>
</variable>
</variable-definition>
<module-override>
<module-name>MyWorkManagerDemo</module-name>
<module-type>war</module-type>
<module-descriptor external="true">
<root-element>weblogic-web-app</root-element>
<uri>WEB-INF/weblogic.xml</uri>
<variable-assignment>
<name>firstVariableName</name>
<xpath>/weblogic-web-app/wl-dispatch-policy</xpath>
</variable-assignment>
</module-descriptor>
</module-override>
<config-root>/opt/apps/</config-root>
</deployment-plan>
.
.
Step7). Now Login to AdminConsole then Update your Application …while updating your Application it will ask for the “plan.xml” file Location…just browse for this file… While updating your WebApplication with “plan.xml” file please choose the following radio button in the AdminConsole:
“Redeploy this application using the following deployment files” FINISH
.
.
Step8). Now hit your application …you will see in the “workload” Subtab of your application then it is being processed by the “myConsoleWorkManager” which is created by us.
.
.
.
Thanks
Jay SenSharma

Copyright © 2010-2012 Middleware Magic. All rights reserved. |