Я использую CXF Framework в своем приложении для реализации остальных услуг. Я пытаюсь интегрировать с атмосферой рамки для любой асинхронной операции. Я изучаю следующий сценарий:
- Пользователь вызывает некоторый rest-метод (
api/atmosphere/fetch
в нашем примере). Обычный http-запрос, без использования сокетов.
- Ресурс приостановки службы отдыха (в нашем примере
r.suspend(30000L);
)
- Служба отдыха запускает любую асинхронную операцию (в нашем примере
new Thread(new AsyncOperation(r.uuid())).start();
. Это может быть отправка сообщения в jms с ожидающим ответом в некотором MessageListener)
- Отправка ответа пользователю после выполнения асинхронной операции (
resource.getResponse().write("Returning response after executing some asynchronous operation"); resource.resume(); resource.close();
)
Но это не работает с cxf (с пружиной работает отлично. Исходные коды приведены ниже). Я ожидаю, что пользователь получит ответ после освобождения ресурса, но фактически пользователь получит пустой ответ сразу после завершения метода fetch
. Служба отдыха возвращает 204 ответа как стандартный результат void
cxf-метода. Есть ли способ использовать suspend
- resume
методы объекта AtmosphereResource
в cxf-приложении?
Мои исходники:
AtmosphereCxfController.java
package controller;
import org.atmosphere.cpr.AtmosphereResource;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
@Path("api/atmosphere")
public class AtmosphereCxfController {
@GET
@Path("/fetch")
public void fetch(@Context HttpServletRequest httpServletRequest) {
AtmosphereResource r = (AtmosphereResource) httpServletRequest.getAttribute("org.atmosphere.cpr.AtmosphereResource");
r.suspend(30000L);
new Thread(new AsyncOperation(r.uuid())).start();
}
}
AsyncOperation.java
package controller;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceFactory;
import java.io.IOException;
//Imitation of long operation
public class AsyncOperation implements Runnable {
private String uuid;
public AsyncOperation(String uuid) {
this.uuid = uuid;
}
public void run() {
try {
Thread.sleep(5000L); //imitation of executing some operation
} catch (Exception e) {
e.printStackTrace();
}
AtmosphereResource resource = AtmosphereResourceFactory.getDefault().find(uuid);
resource.getResponse().write("Returning response after executing some asynchronous operation");
resource.resume();
try {
resource.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
atmosphere.xml
<atmosphere-handlers>
<!-- CXF -->
<atmosphere-handler support-session="false"
context-root="/*"
class-name="org.atmosphere.handler.ReflectorServletProcessor">
<property name="servletClassName"
value="org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet"/>
</atmosphere-handler>
</atmosphere-handlers>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/all.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>cxf</servlet-name>
<servlet-class>org.atmosphere.cpr.AtmosphereServlet</servlet-class>
<init-param>
<param-name>jaxrs.serviceClasses</param-name>
<param-value>
controller.AtmosphereCxfController
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>cxf</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
pom.xml
зависимости и свойства:
<properties>
<springframework.version>3.2.18.RELEASE</springframework.version>
<atmosphere.version>2.1.4</atmosphere.version>
<cxf.version>2.6.0</cxf.version>
<servlet.api.version>2.5</servlet.api.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.api.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.atmosphere</groupId>
<artifactId>atmosphere-runtime</artifactId>
<version>${atmosphere.version}</version>
</dependency>
</dependencies>
all.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:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="apiEndpoint" address="/">
<jaxrs:serviceBeans >
<bean class="controller.AtmosphereCxfController" />
</jaxrs:serviceBeans>
</jaxrs:server>
</beans>
Но то же самое отлично работает, когда я использую весну. Я получаю ожидаемый Returning response after executing some asynchronous operation
ответ от асинхронной операции:
- Пружинный упор
AtmosphereSpringController.java
:
package controller;
import org.atmosphere.cpr.AtmosphereResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping(value = "/api/atmosphere")
public class AtmosphereSpringController {
@RequestMapping(value = "/fetch", method = RequestMethod.GET)
@ResponseBody
public void fetch(HttpServletRequest httpServletRequest) {
AtmosphereResource r = (AtmosphereResource) httpServletRequest.getAttribute("org.atmosphere.cpr.AtmosphereResource");
r.suspend(30000L);
new Thread(new AsyncOperation(r.uuid())).start();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/all.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.atmosphere.cpr.MeteorServlet</servlet-class>
<init-param>
<param-name>org.atmosphere.servlet</param-name>
<param-value>org.springframework.web.servlet.DispatcherServlet</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
spring-servlet.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:mvc="http://www.springframework.org/schema/mvc"
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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
e
<context:component-scan base-package="controller"/>
</beans>
all-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"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
</beans>
pom.xml
зависимости и свойства
<properties>
<springframework.version>4.3.8.RELEASE</springframework.version>
<atmosphere.version>2.1.4</atmosphere.version>
<servlet.api.version>2.5</servlet.api.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.atmosphere</groupId>
<artifactId>atmosphere-runtime</artifactId>
<version>${atmosphere.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.api.version}</version>
</dependency>
</dependencies>
</project>