本文已参加「新人创作礼」活动,一起开启掘金创作之路
本篇内容参考地址,感谢大佬 原文地址
- 下载axis的war包下载地址
- 将下载好的war包部署到tomcat
- 使用方法
1. 第一种
1. 创建一个java类
```java
public class SimpleService
{
public String getGreeting(String name)
{
System.out.println(name);
return "hello===== " + name;
}
public int getPrice()
{
return new java.util.Random().nextInt(1000);
}
}
```
2. 编译java类,将编译好的class文件放在`apache-tomcat-8.5.58\webapps\axis2\WEB-INF\pojo`下,pojo文件夹没有就创建
3. 修改或添加默认的pojo文件夹-->`apache-tomcat-8.5.58\webapps\axis2\WEB-INF\conf`-->`<deployer extension=".class" directory="pojo" class="org.apache.axis2.deployment.POJODeployer"/>`
4. 修改热部署或热更新
`<parameter name="hotdeployment">true</parameter>`` <parameter name="hotupdate">true</parameter>`
2. 第二种
1. 创建一个基本的maven项目,添加依赖
```xml
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-adb</artifactId>
<version>1.7.9</version>
</dependency>
```
2. 在resource下创建文件夹`META-INF`,在该文件夹创建services.xml内容参考
```xml
<?xml version="1.0" encoding="UTF-8"?>
<--多个使用serviceGroup在外面包围-->
<service name="HelloWorld" scope="application">
<description>测试</description>
<!-- 类-->
<parameter name="ServiceClass">cn.jaminye.HelloWorld</parameter>
<!-- 无返回值方法-->
<operation name="testHello">
<messageReceiver mep="http://www.w3.org/ns/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
</operation>
<!-- 又返回值方法-->
<operation name="plus">
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"></messageReceiver>
</operation>
</service>
```
import javax.jws.WebParam;
/**
* 测试
*
* @author Jamin
* @date 2021/1/5 9:05
*/
public class HelloWorld {
/**
* 无返回值
*
* @param message
* @author Jamin
* @date 2021/1/5 9:16
*/
public void testHello(@WebParam String message) {
System.out.println(message);
}
/**
* 有返回值
*
* @param x
* @param y
* @return {@link int}
* @author Jamin
* @date 2021/1/5 9:15
*/
public int plus(@WebParam int x, @WebParam int y) {
return x + y;
}
}
3. 将项目打成jar包放在`apache-tomcat-8.5.58\webapps\axis2\WEB-INF\services`
4. 启动tomcat,打开http://localhost:8080/axis2/services/listServices查看所有服务
5. 点击查看该服务的wsdl文件说明书
6. 输入http://localhost:8080/axis2/services/HelloWorld/plus?x=1&y=2查看返回的xml数据
8. 代码调用
1. 第一种rpc调用
```java
// 使用rpc的方式调用 无返回值
Options options1 = rpcServiceClient.getOptions();
//地址
options1.setTo(new EndpointReference("http://localhost:8080/axis2/services/HelloWorld/testHello"));
//参数
Object[] inArgs1 = {"测试"};
//命名空间
QName qName1 = new QName("jaminye.cn", "testHello");
rpcServiceClient.invokeRobust(qName1, inArgs1);
//使用rpc的方式调用 有返回值
RPCServiceClient rpcServiceClient = new RPCServiceClient();
Options options = rpcServiceClient.getOptions();
//指定调用地址
options.setTo(new EndpointReference("http://localhost:8080/axis2/services/HelloWorld"));
//指定入参与出参类型
Object[] inArgs = {1, 2};
Class[] classes = {String.class};
QName qName = new QName("http://jaminye.cn", "plus");
System.out.println(rpcServiceClient.invokeBlocking(qName, inArgs, classes)[0]);
```
2. 第二种 根据入参
```java
//无返回值调用
ServiceClient serviceClient = new ServiceClient();
Options options = serviceClient.getOptions();
options.setTo(new EndpointReference("http://localhost:8080/axis2/services/HelloWorld"));
options.setAction("http://jaminye.cn/HelloWorld");
OMFactory omFactory = OMAbstractFactory.getOMFactory();
OMNamespace omNamespace = omFactory.createOMNamespace("http://jaminye.cn", "");
OMElement method = omFactory.createOMElement("testHello", omNamespace);
OMElement paramsName = omFactory.createOMElement("message", omNamespace);
paramsName.setText("测试");
method.addChild(paramsName);
method.build();
serviceClient.sendRobust(method);
//有返回值调用
ServiceClient serviceClient = new ServiceClient();
Options options = serviceClient.getOptions();
options.setTo(new EndpointReference("http://localhost:8080/axis2/services/HelloWorld"));
options.setAction("http://jaminye.cn/HelloWorld");
OMFactory omFactory = OMAbstractFactory.getOMFactory();
OMNamespace omNamespace = omFactory.createOMNamespace("http://jaminye.cn", "");
OMElement method = omFactory.createOMElement("plus", omNamespace);
OMElement paramsX = omFactory.createOMElement("x", omNamespace);
paramsX.setText("1");
OMElement paramsY = omFactory.createOMElement("y", omNamespace);
paramsY.setText("2");
method.addChild(paramsX);
method.addChild(paramsY);
method.build();
OMElement result = serviceClient.sendReceive(method);
//返回原来的xml
System.out.println(result);
//获取真正的返回值
System.out.println(result.getFirstElement().getText());
```
3. 复合数据类型
```java
/**
* 上传字节
*
* @param imageByte
* @return {@link boolean}
* @author Jamin
* @date 2021/1/14 9:33
*/
public boolean uploadImageWithByte(byte[] imageByte) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("d:\\1.jpeg");
fileOutputStream.write(imageByte, 0, imageByte.length);
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
return false;
}
/**
* 无参返回数组
*
* @param
* @return {@link String[]}
* @author Jamin
* @date 2021/1/19 15:46
*/
public String[] returnArray() {
String[] strings = {"1", "2", "3", "4"};
return strings;
}
/**
* 返回一个对象
*
* @param
* @return {@link cn.jaminye.HelloWorld.Person}
* @author Jamin
* @date 2021/1/19 15:49
*/
public Person returnPerson() {
return new Person("1", "测试", "13");
}
/**
* 返回对象字节数组
*
* @param
* @return {@link byte[]}
* @author Jamin
* @date 2021/1/19 15:56
*/
public byte[] returnBytes() throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
Person person = new Person("1", "测试", "13");
oos.writeObject(person);
return bos.toByteArray();
}
public class Person implements Serializable{
/**
* id
*/
private String id;
/**
* name
*/
private String name;
/**
* age
*/
private String age;
public Person(String id, String name, String age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
```
```console
org.apache.axis2.AxisFault: cn.jaminye.Person
Caused by: java.lang.InstantiationException: cn.jaminye.Person
Caused by: java.lang.NoSuchMethodException: cn.jaminye.Person.<init>()
实体类没有无参构造方法
```
```java
/**
* 字节数组入参
*
* @throws IOException
*/
@Test
public void testArray() throws IOException {
RPCServiceClient rpcServiceClient = new RPCServiceClient();
Options options = rpcServiceClient.getOptions();
//指定调用地址
options.setTo(new EndpointReference("http://localhost:8080/axis2/services/HelloWorld"));
new File("d:\\1.jpeg").createNewFile();
File file = new File("D:\\Windows\\Pictures\\Camera Roll\\2.jpg");
FileInputStream fis = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fis.read(bytes);
System.out.println("文件长度====" + file.length());
Object[] inArgs = {bytes};
Class[] classes = {Boolean.class};
QName qName = new QName("http://jaminye.cn", "uploadImageWithByte");
fis.close();
System.out.println(rpcServiceClient.invokeBlocking(qName, inArgs, classes)[0]);
}
/**
* 返回对象
* @throws AxisFault
*/
@Test
public void testPerson() throws AxisFault {
RPCServiceClient rpcServiceClient = new RPCServiceClient();
Options options = rpcServiceClient.getOptions();
//指定调用地址
options.setTo(new EndpointReference("http://localhost:8080/axis2/services/HelloWorld"));
Object[] inArgs = {};
Class[] classes = {Person.class};
QName qName = new QName("http://jaminye.cn", "returnPerson");
System.out.println((Person) rpcServiceClient.invokeBlocking(qName, inArgs, classes)[0]);
}
/**
* 返回对象
*
* @throws AxisFault
*/
@Test
public void testPerson() throws AxisFault {
RPCServiceClient rpcServiceClient = new RPCServiceClient();
Options options = rpcServiceClient.getOptions();
//指定调用地址
options.setTo(new EndpointReference("http://localhost:8080/axis2/services/HelloWorld"));
Object[] inArgs = {};
Class[] classes = {Person.class};
QName qName = new QName("http://jaminye.cn", "returnPerson");
System.out.println((Person) rpcServiceClient.invokeBlocking(qName, inArgs, classes)[0]);
}
/**
* 返回字节数组对象
*对象需要实现序列化接口
* @param
* @author Jamin
* @date 2021/1/27 8:48
*/
@Test
void testBytes() throws IOException, ClassNotFoundException {
RPCServiceClient rpcServiceClient = new RPCServiceClient();
Options options = rpcServiceClient.getOptions();
options.setTo(new EndpointReference("http://localhost:8080/axis2/services/HelloWorld"));
QName qName = new QName("http://jaminye.cn", "returnBytes");
Class[] classes = {byte[].class};
byte[] bytes = (byte[]) rpcServiceClient.invokeBlocking(qName, new Object[]{}, classes)[0];
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
Person person = (Person) ois.readObject();
System.out.println(person.toString());
}
```
8. 作用域详细信息
1. request 请求域
2. soapsession
3. TransportSession 会话域 不加managesession 和request差不多 加上和TransportSession
4. Application 应用域
9. 获取与保存当前作用域信息
java MessageContext messageContext=MessageContext.getCurrentMessageContext(); ServiceContext sc = messageContext.getServiceContext(); //保存值 Object previousValue = sc.setProperty("VALUE"); //获取值 Object previousValue = sc.getProperty("VALUE");
10. 跨服务获取信息
1. 将值保存在ServiceGroupContext/ServiceContext
2. 作用域改为application
3. 调用ServiceContext需要开启session管理
11. 异步调用
java rpcServiceClient = new RPCServiceClient(); Options options = rpcServiceClient.getOptions(); options.setTo(new EndpointReference("http://localhost:8080/axis2/services/HelloWorld")); options.setManageSession(true); QName qName = new QName("http://jaminye.cn", "asynchronousCall"); //异步调用 rpcServiceClient.invokeNonBlocking(qName, new Object[]{}, new AxisCallback() { //异步处理 @Override public void onMessage(MessageContext msgContext) { System.out.println(msgContext.getEnvelope().getBody().getFirstElement().getFirstElement().getText()); } @Override public void onFault(MessageContext msgContext) { System.out.println("onFault"); } @Override public void onError(Exception e) { System.out.println(e); } @Override public void onComplete() { } }); System.out.println("结束==========>"); System.in.read();
- 自定义模块 LoggingModule
- 编写module类 实现org.apache.axis2.modules.Module接口 主要方法为init方法
public class LoggingModule implements Module { @Override public void init(ConfigurationContext configContext, AxisModule module) throws AxisFault { System.out.println("======================>init"); } @Override public void engageNotify(AxisDescription axisDescription) throws AxisFault { } @Override public boolean canSupportAssertion(Assertion assertion) { return false; } @Override public void applyPolicy(Policy policy, AxisDescription axisDescription) throws AxisFault { } @Override public void shutdown(ConfigurationContext configurationContext) throws AxisFault { System.out.println("=========================shutdown"); }
}
2. 编写LogHandler类继承org.apache.axis2.handlers.AbstractHandler 实现org.apache.axis2.engine.Handler java
public class LogHandler extends AbstractHandler implements Handler {
private static Log log = LogFactory.getLog(LogHandler.class);
@Override
public InvocationResponse invoke(MessageContext msgContext) throws AxisFault {
log.info("returnMsg====================>{}" + msgContext.getEnvelope().toString());
return InvocationResponse.CONTINUE;
}
}
3. 在resource创建module.xml xml
<OutFaultFlow>
<handler name="FaultOutFlowLogHandler" class="cn.jaminye.util.LogHandler">
<order phase="loggingPhase"/>
</handler>
</OutFaultFlow>
<InFaultFlow>
<handler name="FaultInFlowLogHandler" class="cn.jaminye.util.LogHandler">
<order phase="loggingPhase"/>
</handler>
</InFaultFlow>
```
4. 带依赖打包,改为mar结尾,放在axis2\WEB-INF\modules目录下
5. webapps\axis2\WEB-INF\conf下axis2.xml [InFlow,OutFlow,InFaultFlow,OutFaultFlow] 末尾加上``
6. 需要使用的服务中添加