龙空技术网

MuleESB实例开发

沧澜孤城 131

前言:

此刻兄弟们对“document获取值”都比较关切,你们都想要分析一些“document获取值”的相关资讯。那么小编在网上收集了一些对于“document获取值””的相关文章,希望看官们能喜欢,看官们一起来了解一下吧!

基于AnypointStudio IDE开发MuleESB实例

本文部分内容引用,在此,对原著作者表示感谢。

一、AnypointStudio IDE环境的安装

1.安装jdk1.8以上

2.MuleESB分为社区版和企业版,两者的区别如下:

3.mule esb的开发,主要是在AnypointStudio IDE环境下开发的,所以首先需要下载一个AnypointStudio IDE,本文下载的是6.6.4版本。安装过程和eclipse一样。

由于Anypoint Studio默认只内嵌了Mule ESB企业版运行环境,如果你想使用社区版的话,我们还需要安装Mule ESB社区版运行环境。

安装社区版运行环境,可以使用下列步骤。

点击Help/Install New Software...菜单

在Work with下拉框中选择Mule Runtimes for Anypoint Studio

选中Mule ESB Server Runtime 3.9.0 CE,CE就是Community Edition,社区版的意思。然后点击Next一直到完成。

本例是实现一个cxf的webservice服务封装为http服务。

首先,需要自行开发一个webservice的服务端程序。

 <dependencies>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter</artifactId>    </dependency>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-test</artifactId>        <scope>test</scope>        <exclusions>            <exclusion>                <groupId>org.junit.vintage</groupId>                <artifactId>junit-vintage-engine</artifactId>            </exclusion>        </exclusions>    </dependency>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-web</artifactId>    </dependency>    <!--WerbService CXF依赖-->    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-web-services</artifactId>        <version>2.2.5.RELEASE</version>    </dependency>    <dependency>        <groupId>org.apache.cxf</groupId>        <artifactId>cxf-spring-boot-starter-jaxws</artifactId>        <version>3.3.5</version>    </dependency>    <dependency>        <groupId>commons-io</groupId>        <artifactId>commons-io</artifactId>        <version>2.5</version>    </dependency></dependencies>

@WebService(name = "helloService",targetNamespace=";)

public interface HelloService {

@WebMethod

String sayHello(@WebParam(name="param") Person person);

}

@Service

@WebService(targetNamespace=";,

serviceName = "helloService",

endpointInterface = "com.cbi.cxf.server.service.HelloService")

public class HelloServiceImpl implements HelloService {

@Override

public String sayHello(@WebParam(name="param") Person person) {

System.out.println("receive:"+person.getName()+","+person.getAge());

return "hello,"+person.getName()+","+person.getAge();

}

}

  

@Configurationpublic class WebServiceConfig {    @Autowired    private HelloService helloService;    @Autowired    private SpringBus springBus;    @Bean(name = "helloServiceEndPoint")    public Endpoint endpoint() {        EndpointImpl endpoint=new EndpointImpl(springBus, helloService);//绑定要发布的服务        endpoint.publish("/helloWs"); //显示要发布的名称        return endpoint;    }

public class Person implements Serializable {      private static final long serialVersionUID = 1L;   private String name;      private String age;   public String getName() {      return name;   }   public void setName(String name) {      this.name = name;   }   public String getAge() {      return age;   }   public void setAge(String string) {      this.age = string;   }}

服务端程序开发完成之后启动,访问,即可得到如下wsdl:

<wsdl:definitions xmlns:xsd="; xmlns:wsdl="; xmlns:tns="; xmlns:soap="; xmlns:ns1="; name="helloService" targetNamespace=";><wsdl:types><xs:schema xmlns:xs="; xmlns:tns="; elementFormDefault="unqualified" targetNamespace="; version="1.0"><xs:element name="sayHello" type="tns:sayHello"/><xs:element name="sayHelloResponse" type="tns:sayHelloResponse"/><xs:complexType name="sayHello"><xs:sequence><xs:element minOccurs="0" name="param" type="tns:person"/></xs:sequence></xs:complexType><xs:complexType name="person"><xs:sequence><xs:element minOccurs="0" name="age" type="xs:string"/><xs:element minOccurs="0" name="name" type="xs:string"/></xs:sequence></xs:complexType><xs:complexType name="sayHelloResponse"><xs:sequence><xs:element minOccurs="0" name="return" type="xs:string"/></xs:sequence></xs:complexType></xs:schema></wsdl:types><wsdl:message name="sayHelloResponse"><wsdl:part element="tns:sayHelloResponse" name="parameters"> </wsdl:part></wsdl:message><wsdl:message name="sayHello"><wsdl:part element="tns:sayHello" name="parameters"> </wsdl:part></wsdl:message><wsdl:portType name="helloService"><wsdl:operation name="sayHello"><wsdl:input message="tns:sayHello" name="sayHello"> </wsdl:input><wsdl:output message="tns:sayHelloResponse" name="sayHelloResponse"> </wsdl:output></wsdl:operation></wsdl:portType><wsdl:binding name="helloServiceSoapBinding" type="tns:helloService"><soap:binding style="document" transport=";/><wsdl:operation name="sayHello"><soap:operation soapAction="" style="document"/><wsdl:input name="sayHello"><soap:body use="literal"/></wsdl:input><wsdl:output name="sayHelloResponse"><soap:body use="literal"/></wsdl:output></wsdl:operation></wsdl:binding><wsdl:service name="helloService"><wsdl:port binding="tns:helloServiceSoapBinding" name="HelloServiceImplPort"><soap:address location=";/></wsdl:port></wsdl:service></wsdl:definitions>

6.使用AnypointStudio开发mule ESB的服务。

根据实际选择运行环境,一直next下去,完成即可。

工程依赖包:

工程http2webservice创建好之后,按照区域1拖拽出流程,按照区域3编写java代码,区域2是在拖拽流程的过程中,可以搜索需要的组件。

public class Person implements Serializable {private static final long serialVersionUID = 1L;private String name;private String age;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAge() {return age;}public void setAge(String string) {this.age = string;}}

public class Trans  extends AbstractMessageTransformer{@Overridepublic Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {String xml="";try {xml=message.getPayloadAsString();Document doc=DocumentHelper.parseText(xml);Element root=doc.getRootElement();   Person person=new Person();person.setName(root.element("name").getText());person.setAge(root.element("age").getText());JSONObject node = new JSONObject();node.put("param",  person);System.out.println("node==================="+node);Map<String, Object> newMap=TransUtil.parseJSONToMap(node.toString());System.out.println("newMap==================="+newMap);xml=TransUtil.parseMapToXML(newMap, "sayHello", ";);} catch (Exception e) {e.printStackTrace();}System.out.println("xml==================="+xml);return xml;}}

public class ReturnTrans  extends AbstractMessageTransformer{@Overridepublic Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {Object payload=message.getPayload();DepthXMLStreamReader xmlreader=(DepthXMLStreamReader) payload;XMLStreamReader reader=xmlreader.getReader();String returnxml="";try {while(reader.hasNext()) {int point =reader.next();if(point==XMLStreamReader.START_ELEMENT) {String eleName=reader.getName().toString();if("return".equals(eleName)) {returnxml=reader.getElementText();break;}}}} catch (XMLStreamException e) {e.printStackTrace();}returnxml="<result>"+returnxml+"</result>";System.out.println("xml==================="+returnxml);return returnxml;}

public class TransUtil {public static Map<String,Object> parseJSONToMap(String jsonStr){  Map<String, Object> map = new HashMap<>();       JSONObject json = JSONObject.fromObject(jsonStr);       for (Object k : json.keySet()) {           Object v = json.get(k);           if (v instanceof JSONArray) {               List<Map<String, Object>> list = new ArrayList<>();               Iterator<JSONObject> it = ((JSONArray) v).iterator();               while (it.hasNext()) {                   JSONObject json2 = it.next();                   list.add(parseJSONToMap(json.toString()));               }               map.put(k.toString(), list);           } else {               map.put(k.toString(), v);           }       }       return map;}public static String parseMapToXML(Map<String,Object> map,String method,String nameSpace) {if (map == null) return null;     JSONObject json = JSONObject.fromObject(map);     XMLSerializer ser = new XMLSerializer();     ser.setRootName("tem:" + method);     ser.write(json);     ser.setNamespace("tem", nameSpace);     ser.setTypeHintsEnabled(false);     String result = ser.write(json, "UTF-8");     return result;}public static Map<String, Object> multilayerXmlToMap(String xml) {    Document doc = null;    try {        doc = DocumentHelper.parseText(xml);    } catch (DocumentException e) {        e.printStackTrace();    }    Map<String, Object> map = new HashMap<>();    if (null == doc) {        return map;    }    // 获取根元素    Element rootElement = doc.getRootElement();    recursionXmlToMap(rootElement,map);    return map;}/** * multilayerXmlToMap核心方法,递归调用 *  * @param element 节点元素 * @param outmap 用于存储xml数据的map */private static void recursionXmlToMap(Element element, Map<String, Object> outmap) {    // 得到根元素下的子元素列表    List<Element> list = element.elements();    int size = list.size();    if (size == 0) {        // 如果没有子元素,则将其存储进map中        outmap.put(element.getName(), element.getTextTrim());    } else {        // innermap用于存储子元素的属性名和属性值        Map<String, Object> innermap = new HashMap<>();        // 遍历子元素        list.forEach(childElement -> recursionXmlToMap(childElement, innermap));        outmap.put(element.getName(), innermap);    }}}

按照如上图的配置完成之后,可以启动工程。在工程上右键run as mule application即可。

7.测试

cxf服务客户端测试:

方式一:动态调用

public class TestClient {    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, ClassNotFoundException, InstantiationException {        // 创建动态客户端        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();        Client client = dcf.createClient(";);        // 需要密码的情况需要加上用户名和密码        // client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));        Object[] result = null;        //loadClass路径是命名空间+po类名,不是Po的包路径+po类名        Object po = Thread.currentThread().getContextClassLoader().loadClass("com.cbi.cxf.service.Person").newInstance();//加载类为服务端自定义对象命名空间        Method method = po.getClass().getMethod("setName", String.class);//调用set方法设置参数        method.invoke(po, "卓宝贝");        method = po.getClass().getMethod("setAge", String.class);//调用set方法设置参数        method.invoke(po, "6");        Object[] parameters = new Object[]{po};        try {            result = client.invoke("sayHello", parameters);//uploadcs为接口方法            System.out.println(result[0].toString());        } catch (Exception e) {            e.printStackTrace();        }    }

方式二:静态调用

public class TestClient2 {    public static void main(String[] args) {        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();        factory.setAddress(";);        factory.setServiceClass(HelloService.class);//服务端接口类        Person person = new Person();//自定义对象参数        person.setName("卓宝贝");        person.setAge("6");        HelloService service = (HelloService) factory.create();        String results = service.sayHello(person);//sayHello为接口方法        System.out.println(results);    }}

两种方式测试原始的webservice接口的结果相同,如下:

hello,卓宝贝,6

使用postman测试封装的http接口:post方式

返回结果说明:

如果返回结果要和原始的webservice接口保持一致,流程图中的最后一个节点需要去掉。

如果返回结果需要用json表示,则需要在ReturnTrans类中或者在webservice接口返回时,先拼接成xml格式,然后xml to json节点才会正确转换,否则会报错,如下:

最终获得的结果json格式如下:

{"result": "hello,卓宝贝,6"}

标签: #document获取值 #post 返回值