I'm trying to get Memcache working in Spring.
I've setup a local Memcached server using Docker and Kitematic:
I can access the Memcached server using telnet: telnet 192.168.99.100 32780 and then run stats or stats items (which only prints out END if the cache is empty);
My pom.xml:
<dependency>
<groupId>com.google.code.simple-spring-memcached</groupId>
<artifactId>simple-spring-memcached</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>com.google.code.simple-spring-memcached</groupId>
<artifactId>spring-cache</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>com.google.code.simple-spring-memcached</groupId>
<artifactId>xmemcached-provider</artifactId>
<version>3.6.0</version>
</dependency>
In my applicationContext.xml I have the following:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>
...
<import resource="cacheContext.xml" />
...
In cacheContext.xml my config is as follow:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<aop:aspectj-autoproxy/>
<cache:annotation-driven/>
<context:component-scan base-package="com.google.code.ssm"/>
<context:component-scan base-package="com.mycee.application"/>
<bean id="cacheBase" class="com.google.code.ssm.aop.CacheBase"/>
<bean id="readThroughSingleCache" class="com.google.code.ssm.aop.ReadThroughSingleCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="readThroughMultiCache" class="com.google.code.ssm.aop.ReadThroughMultiCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="readThroughAssignCache" class="com.google.code.ssm.aop.ReadThroughAssignCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="updateSingleCache" class="com.google.code.ssm.aop.UpdateSingleCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="updateMultiCache" class="com.google.code.ssm.aop.UpdateMultiCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="updateAssignCache" class="com.google.code.ssm.aop.UpdateAssignCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="invalidateSingleCache" class="com.google.code.ssm.aop.InvalidateSingleCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="invalidateMultiCache" class="com.google.code.ssm.aop.InvalidateMultiCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="invalidateAssignCache" class="com.google.code.ssm.aop.InvalidateAssignCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="incrementCounterInCache" class="com.google.code.ssm.aop.counter.IncrementCounterInCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="decrementCounterInCache" class="com.google.code.ssm.aop.counter.DecrementCounterInCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="readCounterFromCache" class="com.google.code.ssm.aop.counter.ReadCounterFromCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="updateCounterInCache" class="com.google.code.ssm.aop.counter.UpdateCounterInCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean name="cacheManager" class="com.google.code.ssm.spring.SSMCacheManager">
<property name="caches">
<set>
<bean class="com.google.code.ssm.spring.SSMCache">
<constructor-arg name="cache" index="0" ref="defaultCache"/>
<constructor-arg name="expiration" index="1" value="300"/>
<constructor-arg name="allowClear" index="2" value="false"/>
</bean>
</set>
</property>
</bean>
<bean name="defaultCache" class="com.google.code.ssm.CacheFactory" depends-on="cacheBase">
<property name="cacheName" value="defaultCache"/>
<property name="cacheClientFactory">
<bean class="com.google.code.ssm.providers.xmemcached.MemcacheClientFactoryImpl"/>
</property>
<property name="addressProvider">
<bean class="com.google.code.ssm.config.DefaultAddressProvider">
<property name="address" value="localhost:11211"/>
</bean>
</property>
<property name="configuration">
<bean class="com.google.code.ssm.providers.CacheConfiguration">
<property name="consistentHashing" value="true"/>
</bean>
</property>
</bean>
</beans>
I've created three different methods, each using different caching mechanisms:
#Component("cacheEndpoint")
public class CacheClass {
#Autowired
SSMCacheManager cache;
public String getDateTime1(String anything) {
SSMCache c = cache.getCache("defaultCache");
String s = c.get(anything, String.class);
if (s != null) {
return s;
}
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
c.put(anything, response);
return response;
}
#Cacheable("defaultCache")
public String getDateTime2(String anything) {
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
return response;
}
#ReadThroughSingleCache(namespace = "defaultCache", expiration = 15000)
public String getDateTime3(String anything) {
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
return response;
}
}
To access it I do:
#Autowired
CacheClass c;
...
// caches perfectly
c.getDateTime1("test");
// doesn't do any caching
c.getDateTime2("test");
// doesn't do any caching
c.getDateTime3("test");
After placing runtime exceptions in getDateTime2 and getDateTime3, it was established that the interceptors aren't being invoked.
Any idea what could be the cause of #Cachable and #ReadThroughSingleCache not doing their interception magic?
Update based on Matjaž Pečan's response:
CacheClass Interface:
public interface CacheClass {
public String getDateTime1(String anything);
public String getDateTime2(String anything);
public String getDateTime3(String anything);
}
CacheClass Implementation:
#Component("cacheEndpoint")
public class CacheClassImpl implements CacheClass {
#Autowired
SSMCacheManager cache;
public String getDateTime1(String anything) {
SSMCache c = cache.getCache("defaultCache");
String s = c.get(anything, String.class);
if (s != null) {
return s;
}
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
c.put(anything, response);
return response;
}
#Cacheable("defaultCache")
public String getDateTime2(String anything) {
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
return response;
}
#ReadThroughSingleCache(namespace = "defaultCache", expiration = 15000)
public String getDateTime3(String anything) {
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
return response;
}
}
SOAP Endpoint where I'm testing the cache:
#Endpoint
public class PingEndpoint {
#Autowired
CacheClass c;
#ResponsePayload
#PayloadRoot(localPart = "PingRequest", namespace = "http://www.mycee.com/Application")
public PingResponse doPing(#RequestPayload PingRequest request) {
// caches perfectly
System.out.println(c.getDateTime1("test"));
// doesn't do any caching
System.out.println(c.getDateTime2("test"));
// doesn't do any caching
System.out.println(c.getDateTime3("test"));
}
}
cacheContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<aop:aspectj-autoproxy proxy-target-class="true"/>
<cache:annotation-driven/>
...
There is an error in SSM 3.6.0, please downgrade to 3.5.0 to solve the issue or try to add
depends-on="cacheBase"
to defaultCache bean definition.
Update 1
Self invocations don't work. A call won't be intercepted and result won't be cached if a invocation is through this object. Make sure that method defined in a bean is invoked from another Spring bean.
Update 2
For SSM method has to be annotated as below:
#ReadThroughSingleCache(namespace = "defaultCache", expiration = 15000)
public String getDateTime3(#ParameterValueKeyProvider String anything) {
...
}
Still interceptors for some reasons aren't triggered.
Spring proxying mechanisms differ depending on which implementation is used.
The default is AspectJ which requires interfaces (proxy-by-interface) and those interfaces will then be implemented by the actual proxy wrapped around your bean. Since your bean is only a class and does not have an interface, it is not proxied with AspectJ.
There are two possible solutions:
Implement an interface for CacheClass and use that interface in wiring to other beans
Use CGLib proxying (you will need to add a runtime dependency on CGLib) and add proxy-target-class in your aspectj-proxy element:
<aop:aspectj-autoproxy proxy-target-class="true"/>
Related
I have a sample code in which I am trying to convert application-context.xml to Spring annotated Java class. How to add constructor-arg with proper annotations here. Could you please help me sort this.
application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:component-scan base-package="myproject"/>
<!-- Define the SOAP version used by the WSDL -->
<bean id="soapMessageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
<property name="soapVersion">
<util:constant static-field="org.springframework.ws.soap.SoapVersion.SOAP_12"/>
</property>
</bean>
<!-- The location of the generated Java files -->
<oxm:jaxb2-marshaller id="marshaller" contextPath="myproject.wsdl.currency"/>
<!-- Configure Spring Web Services -->
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="soapMessageFactory"/>
<property name="marshaller" ref="marshaller"/>
<property name="unmarshaller" ref="marshaller"/>
<property name="defaultUri" value="http://www.webservicex.net/CurrencyConvertor.asmx?WSDL"/>
</bean>
<bean id="example" class="org.project.Example"/>
I have created Config.class as below.
#Configuration
public class AppConfig {
#Bean(name="soapMessageFactory")
public SaajSoapMessageFactory getSoapMsgFactory() {
SaajSoapMessageFactory soapFactory = new SaajSoapMessageFactory();
soapFactory.setSoapVersion(SoapVersion.11);
return soapFactory;
}
#Bean(name="webServiceTemplate")
public WebServiceTemplate getWsTemplate(Marshaller marshaller, Unmarshaller unmarshaller) {
WebServiceTemplate wsTemplate = new WebServiceTemplate();
//how to configure the constructor-arg here
wsTemplate.setMarshaller(marshaller);
wsTemplate.setUnMarshaller(unmarshaller);
wsTemplate.setDefaultUri(http://www.webservicex.net/CurrencyConvertor.asmx?WSDL);
return wsTemplate;
}
#Bean(name="example")
public Example getExample() {
return new ExampleImpl();
}
This should work...
#Bean(name="soapMessageFactory")
public SaajSoapMessageFactory getSoapMsgFactory() {
SaajSoapMessageFactory soapFactory = new SaajSoapMessageFactory();
soapFactory.setSoapVersion(SoapVersion.11);
return soapFactory;
}
#Bean(name="webServiceTemplate")
public WebServiceTemplate getWsTemplate(SaajSoapMessageFactory soapFactory, Marshaller marshaller, Unmarshaller unmarshaller) {
WebServiceTemplate wsTemplate = new WebServiceTemplate(soapFactory);
wsTemplate.setMarshaller(marshaller);
wsTemplate.setUnMarshaller(unmarshaller);
wsTemplate.setDefaultUri(http://www.webservicex.net/CurrencyConvertor.asmx?WSDL);
return wsTemplate;
}
When you specify any dependecy in #Bean method, spring will search for that bean in its context.
Since SaajSoapMessageFactory is locally created and doesn't have any other dependency, you could just call it locally like this
WebServiceTemplate wsTemplate = new WebServiceTemplate(getSoapMsgFactory());
I am trying to pass string messages from one class to another (from Class1 to Class2) within the same application so I am trying to solve it using Spring Integration.
My context.xml file looks like below:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/jms http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-jms="http://www.springframework.org/schema/integration/jms">
<int:channel id="processEmpChannel">
<int:queue/>
</int:channel>
<int-jms:inbound-channel-adapter
channel="processEmpChannel" connection-factory="connectionFactory"
destination-name="empQueue">
<int:poller fixed-delay="500" />
</int-jms:inbound-channel-adapter>
<bean id="connectionFactory"
class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory">
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="vm://localhost?broker.persistent=false" />
</bean>
</property>
<property name="sessionCacheSize" value="10" />
<property name="cacheProducers" value="false" />
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
<bean id="springIntExample"
class="com.distributed.analyzer.Manager">
<property name="jmsTemplate" ref="jmsTemplate" />
</bean>
<int:service-activator input-channel="processEmpChannel" ref="springIntExample" method="processMessage">
<int:poller fixed-delay="500"/>
</int:service-activator>
</beans>
Class Class1:
package com.my.package;
public class Class1 implements Runnable {
#Autowired
private ApplicationContext appContext;
private JmsTemplate jmsTemplate;
...
public void someMethod() {
Class1 c = (Class1) appContext.getBean("springIntExample");
c.send();
}
public void send() {
getJmsTemplate().convertAndSend("empQueue", "one message to test");
}
public JmsTemplate getJmsTemplate() {
return jmsTemplate;
}
public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
...
}
Class Class2:
package com.my.package;
public class Class2 implements Runnable {
...
public void processMessage(String msg) {
System.out.println("message recived: " + msg);
}
...
}
Problem I have:
If I open my context.xml file, the below lines in context.xml are marked with a cross (error):
<int:poller fixed-delay="500" />
Anyway I can build and execute application but in run time an exception message saying fixe-delay not allowed in int:poller appears.
Also, is my implementation correct? I am not sure if after solving the problem commented it will work. I am new in spring sorry.
Some prehistory..
I have a web-based corporate CRM system written with Spring and Hibernate. There are a lot of tasks that should be done systematically such as reminders or email notifications.. Now it is implemented as a separate Controller wich is called from cron. Everything works fine except of the fact that some of tasks are very "heavy" and take a lot of Tomcat's resources. So I decided to split them into different java console apps. In order to use the same objects and services I splited the main project into separate projects (libraries):
Objects
DAO
In the main project I just added these projects to the BuildPath so I can use all the objects and services without any problem.
Now I started implement the first console utility and facing some issue.. Take a look.
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-service.xml", "spring-hibernate.xml");
try {
MessageSourceEx messageSource = new MessageSourceEx((ResourceBundleMessageSource) ctx.getBean("messageSource"));
ITasksService tasksService = (ITasksService) ctx.getBean("tasksService");
NotificationsService notificationsService = (NotificationsService) ctx.getBean("notificationsService");
List<Task> tasks = tasksService.systemGetList();
for (Task t: tasks) {
Locale userLocale = t.getCreator().getCommunicationLanguageLocale();
EmailNotification reminder = new EmailNotification(t.getCreator().getEmail(),
messageSource.getMessage(userLocale, "notifications.internal.emails.task.subject"),
messageSource.getMessage(userLocale, "notifications.internal.emails.task.text",
t.getCreator().getNickname(),
t.getName(),
t.getDescription(),
AppConfig.getInstance().getUrl(),
t.getId()),
userLocale, t.getCreator());
notificationsService.email.send(reminder);
if (reminder.getState() == EmailNotificationSendState.Sent) {
t.setReminderSent(true);
tasksService.save(t);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
((ConfigurableApplicationContext)ctx).close();
}
System.exit(0);
}
spring-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:annotation-config />
<context:component-scan base-package="com.dao,com.service,com.notifications,com.interfaces" />
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="com.Resources" />
</bean>
</beans>
spring-hibernate.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<tx:annotation-driven />
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:/hibernate.properties" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${hibernate.connection.driver_class}" />
<property name="url" value="${hibernate.connection.url}" />
<property name="username" value="${hibernate.connection.username}" />
<property name="password" value="${hibernate.connection.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.data.Task</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
DAO
#Component
public class TasksDAO {
/**
* Retrieves a list of tasks
*
* #return List of tasks
*/
#SuppressWarnings({ "unchecked" })
public List<Task> systemGetList() {
Session session = SessionFactoryUtils.getSession(sessionFactory, false);
List<Task> result = null;
Date now = new Date();
Criteria query = session.createCriteria(Task.class)
.add(Restrictions.le("remindTime", DateUtilsEx.addMinutes(now, 3)))
.add(Restrictions.eq("reminderSent", false))
.addOrder(Order.asc("remindTime"));
result = query.list();
if (result == null)
result = new ArrayList<Task>();
return result;
}
}
Service
#Service
public class TasksService implements ITasksService {
/**
*
*/
#Override
public List<Task> systemGetList() {
return tasksDAO.systemGetList();
}
}
It fails with No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SessionFactoryUtils.doGetSession(SessionFactoryUtils.java:356) exception.. What is interesting - if I add #Transactional to systemGetList() - works fine. But I don't want to add transactions for all select statements...
And the same code (without transaction) works fine on web-site itself..
Any help? Thank you in advance.
You have specified your service methods to be Transactional
<tx:annotation-driven />
Add #Transactional(readOnly = true) on select/read only methods
I am using Spring 3.1 as standalone app.
I have some wierd situation and I guess I am missing something.
I have class which has method that I have exposed via JMX console.
that method is invoking a method via bean.
that bean I am initializing in advaned.
the wierd thing that after i am invoking the method via the jmx console the bean instance turn to be null.
Thats the JMX bean which is exposed:
public class TriggerBean implements IJmxTriggerBean
{
static Logger logger = Logger.getLogger(TriggerBean.class);
FeedListenerBean fe = null;
public void start()
{
try
{
// init();
PropertyConfigurator.configure(FixGWConstants.LOG4J_PATH);
ApplicationContext context = new ClassPathXmlApplicationContext(FixGWConstants.APPLICATION_CONTEXT_XML);
fe = (FeedListenerBean) context.getBean("FeedListenerBean");
doTheListen();
}
catch (Throwable t)
{
logger.error(t);
System.out.println(t);
}
}
//thats the method being exposed by jmx. pay attention that fe object has been initialized before by the start()
public void doTheListen()
{
fe.listen();
}
private void init()
{
Resource resource = new ClassPathResource(System.getProperty("user.dir") + "//config.properties");
try
{
Properties props = PropertiesLoaderUtils.loadProperties(resource);
String log4jPath = props.getProperty("LOG4J_PATH");
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am testing it via standalone:
public static void main(String[] args) throws Exception
{
protected TriggerBean trigger = new Trigger();
trigger.start();
}
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- Must for auto wiring
<context:annotation-config />
-->
<context:component-scan base-package="com.fixgw.beans">
</context:component-scan>
<!-- start a JMX Server -->
<bean id="mbeanServer" class="org.springframework.jmx.support.MBeanServerFactoryBean" />
<bean id="FeedListenerBean" class="com.fixgw.beans.FeedListenerBean">
</bean>
<bean id="TriggerBean" class="com.fixgw.test.TriggerBean">
</bean>
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="Server:name=HttpAdaptor">
<bean class="mx4j.tools.adaptor.http.HttpAdaptor">
<property name="port" value="8000" />
<property name="host" value="0.0.0.0" />
<property name="processor">
<bean class="mx4j.tools.adaptor.http.XSLTProcessor" />
</property>
</bean>
</entry>
<entry key="bean:name=TriggerBean" value-ref="TriggerBean" />
</map>
</property>
<property name="listeners">
<list>
<!--
let the HttpAdapter be started after it is registered in the
MBeanServer
-->
<bean class="com.fixgw.jmx.HttpAdaptorMgr">
<property name="mbeanServer" ref="mbeanServer" />
</bean>
</list>
</property>
</bean>
</beans>
When I first using start() the object fe is doing great.
but after invoking doTheListen( via JMX the object fe remind null(although it has already been initialized before)
any idea?
thanks,
ray.
I am trying to configure JMX console for my standalone Spring application.
I have configured it this way:
Application context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- Must for auto wiring
<context:annotation-config />
-->
<context:component-scan base-package="com.fixgw.beans">
</context:component-scan>
<bean id="FeedListenerBean" class="com.fixgw.beans.FeedListenerBean">
</bean>
<bean id="TriggerBean" class="com.fixgw.test.TriggerBean">
</bean>
<bean id="mbeanServer" class="org.springframework.jmx.support.MBeanServerFactoryBean" >
<property name="locateExistingServerIfPossible" value="true" />
</bean>
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="bean:name=TriggerBean1" value-ref="TriggerBean" />
</map>
</property>
<property name="server" ref="mbeanServer" />
</bean>
</beans>
And a Trigger bean which I want it's public method to be exposed in the JMX:
public class TriggerBean implements IJmxTriggerBean
{
static Logger logger = Logger.getLogger(TriggerBean.class);
FeedListenerBean fe = null;
public void start()
{
try
{
// init();
PropertyConfigurator.configure(FixGWConstants.LOG4J_PATH);
ApplicationContext context = new ClassPathXmlApplicationContext(FixGWConstants.APPLICATION_CONTEXT_XML);
fe = (FeedListenerBean) context.getBean("FeedListenerBean");
Thread t=new Thread()
{
public void run()
{
while (true)
{
System.out.println("a");
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
t.run();
doTheListen();
}
catch (Throwable t)
{
logger.error(t);
System.out.println(t);
}
}
public void doTheListen()
{
fe.listen();
}
}
package com.finbird.fixgw.test;
public interface IJmxTriggerBean
{
public void doTheListen();
}
Is that enough for configuration?
Now to which local address:port should I connect in order to access the console?
thanks,
ray
You have the JMX server, but you need an HTMLAdapter to view these beans via a browser. e.g. from this article:
<bean id="htmlAdaptor" class="com.sun.jdmk.comm.HtmlAdaptorServer" init-method="start" />
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="adaptor:name=htmlAdaptor" value-ref="htmlAdaptor" />
<entry key="bean:name=calculatorConfigBean" value-ref="calculatorConfig" />
</map>
</property>
<property name="server" ref="mbeanServer" />
</bean>
Note that I'm assuming HTML/browser access here. See here for an Oracle tutorial with an adapter configured in code.