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:\temp\EJB3_With_WorkManager”
.
Step3). Now create a EJB remote Interface “CalculatorRemote.java” inside “C:\temp\EJB3_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:\temp\EJB3_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:\temp\EJB3_With_WorkManager” and then create a file “weblogic-ejb-jar.xml”  inside “C:\temp\EJB3_With_WorkManager\META-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("\n\t Didnot get InitialContext: "+e);
			 }
           try
             {

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

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

                System.out.println("\n\n\t SUM = "+remote.add(Integer.parseInt(ar[0]),Integer.parseInt(ar[1])));
             }
           catch(Exception e)
             {
                System.out.println("\n\n\t jack Exception => "+e);
                e.printStackTrace();
             }
           System.out.println("\n\t 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

WorkManager At WebApplication Level

Hi,

Jay SenSharma

Jay SenSharma

If you want to Assign a Global Work Manager (A Work Manager which is created through AdminConsole).. And if you want more than 1-Thread should not be allocated by the WebLogic to process request for your WebApplication…then you can do the Following:

Provide the Capacity-Constraint to 1

Step1). Configure a WorkManager from Admin Console.

with the following Configuration: in your “config.xml”

<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…
Step2). Write a Simple WebApplication with the following kind of JSP Page:
<%@ page import="java.util.*" %>
<%!
static int counter=0;
%>
<%
session.setAttribute("counter","Counter-"+counter);
counter++;
for(int id=0;id<60;id++)
{
System.out.println(id+"\tRequest Is Being Processsed for :"+(String)session.getAttribute("counter"));
try{
Thread.sleep(1000);
}
catch(Exception e)
{
e.printStackTrace();
}
}
out.println("<h2>Request Processing Completed");
%>
Step3). Now provide the “weblogic.xml” bu providing the Work-Manager name in wl-dispatch-policy annotation:
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app xmlns="http://www.bea.com/ns/weblogic/90">
<wl-dispatch-policy>myConsoleWorkManager</wl-dispatch-policy>
</weblogic-web-app>
Step4). Now deploy the Application and And
you can check it from admin console as well..

AdminConsole–> Home–>Deployment Summary–> (click on your WebApp)–>Monitoring (Tab)—> WorkLoad (Sub-Tab)

Hit your WebApplication and then See …in admin Console…How many request is being processed…

When you send the Concurrent Second request to the WebApplication you will get 503-Service Not Available Error By the WebLogic Server…Because of the Constraint Capicity=1 …weblogic will process only 1 Concurrent request for your WebApplication.

.

.

Thanks

Jay SenSharma



Application Level WorkManager & TimerManager Lookup

Hi,

Jay SenSharma

Jay SenSharma

Most of the time we have observed that many WebLogic Developers and Admins face various issues while configuring and looking up the Application Level WorkManager.

WebLogic Server prioritizes work and allocates threads based on an execution model that takes into account administrator-defined parameters and actual run-time performance and throughput.

Work Managers can be configured at the domain level, application level, and module level in one of the following configuration files:

  • config.xml—Work Managers specified in config.xml can be assigned to any application, or application component, in the domain. You can use the Administration Console to define a Work Manager.
  • weblogic-application.xml—Work Managers specified at the application level can be assigned to that application, or any component of that application.
  • weblogic-ejb-jar.xml or weblogic.xml—Work Managers specified at the component-level can be assigned to that component.
  • weblogic.xml—Work Managers specified for a Web Application.

Here is a Simplest sample we are going to develop…to see how to utilize the Application level Work Managers. It means we need NOT to configure any WorkManager using Admin Console…It will be configured through Deployment Descriptor.

Step1). First of all we will develop the “index.jsp” page to see how to lookup the “commonj.work.WorkManager” and the TimerManager which we are going to configure …

<%@ page import="javax.naming.InitialContext,commonj.timers.TimerManager" %>
<%
System.out.println("\n\n\t ---------------1-------------");
TimerManager timerManager = null;
try {
InitialContext initContext = new InitialContext();
timerManager = (TimerManager) initContext.lookup("java:comp/env/timer/TestTimer");
System.out.println("\n\n\t I am able to Lookup: "+timerManager);
out.println("<b><font color=GREEN>\"timer/TestTimer\" Created Using DD</font> I am able to Lookup:</b>"+timerManager);
}
catch (Throwable anException)
{
throw new RuntimeException(anException);
}
System.out.println("\n\n\t ---------------2-------------");
try {
InitialContext initContext2 = new InitialContext();
commonj.work.WorkManager workManager = (commonj.work.WorkManager)initContext2.lookup("java:comp/env/wm/WorkManagerA");
System.out.println("\n\n\t I am able to Lookup: commonj.work.WorkManager workManager = "+workManager);
out.println("<BR><BR><BR><b><font color=red>Application Level Work Manager.</font>  I am able to Lookup:</b> "+workManager);
}
catch (Throwable anException)
{
System.out.println("\n\n\t Exception Thrown: "+anException);
throw new RuntimeException(anException);
}
System.out.println("\n\n\t ---------------3-------------");
%>

Step2). Now we will develope the “web.xml” here we will provide the reference to the WorkManager and the TimerManager resource -ref

<web-app xmlns="http://java.sun.com/xml/ns/j2ee">
   <resource-ref>
        <res-ref-name>timer/TestTimer</res-ref-name>
        <res-type>commonj.timers.TimerManager</res-type>
        <res-auth>Container</res-auth>
        <res-sharing-scope>Shareable</res-sharing-scope>
  </resource-ref>

  <resource-ref>
        <res-ref-name>wm/WorkManagerA</res-ref-name>
        <res-type>commonj.work.WorkManager</res-type>
        <res-auth>Container</res-auth>
        <res-sharing-scope>Shareable</res-sharing-scope>
        </resource-ref>
</web-app>
Step 3). Now we need to define the <work-manager>  tag in “weblogic.xml” file…
<?xml version="1.0" encoding="ISO-8859-1"?>
<weblogic-web-app xmlns="http://www.bea.com/ns/weblogic/90">
    <work-manager>
       <name>WorkManagerA</name>
       <max-threads-constraint>
          <name>MyMaxThreadCount_2</name>
          <count>2</count>
       </max-threads-constraint>
    </work-manager>
    <wl-dispatch-policy>WorkManagerA</wl-dispatch-policy>
</weblogic-web-app>
Step 4). Now we need to Deploy this Application in WebLogic Server then We will find …Now Login to Admin Console here in “Home—>Deployments—>WorkManagerDemoApp—>Configuration(Tab)—>WorkLoad(Tab)” we can see that WorkManagerA is configured as soon as the deployment was Successful…

.
.
Thanks
Jay SenSharma


  • Testimonials

  • RSS Middleware Magic – JBoss

  • Receive FREE Updates


    FREE Email updates of our new posts Enter your email address:



  • Magic Archives

  • Sitemeter Status

  • ClusterMap 7-Nov-2011 till Date

  • ClusterMap 6-Nov-2010 till 7-Nov-2011

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