Home > Java > javaTutorial > body text

How webservice implements interface calling and object transfer between springboot projects

WBOY
Release: 2023-06-03 12:09:06
forward
1609 people have browsed it

1. Baidu Encyclopedia

Web Service is a platform-independent, low-coupled, self-contained, programmable web-based application that can use open XML (standard universal markup language) A subset) of standards for describing, publishing, discovering, coordinating, and configuring these applications for developing distributed, interoperable applications.

Web Service technology enables different applications running on different machines to exchange data or integrate with each other without the need for additional, specialized third-party software or hardware. Applications implemented according to Web Service specifications can exchange data with each other regardless of the language, platform or internal protocol they use. Web Service is a self-contained, self-describing module that can be used on the network and can perform specific business functions. Web Services are also easy to deploy because they are based on some conventional industry standards and existing technologies, such as subsets of XML and HTTP under the standard universal markup language. Web Services reduce the cost of application interfaces. Web services provide a common mechanism for integrating business processes across an enterprise or even across multiple organizations.

2. Technical support for webservice

To realize the creation of distributed applications, the Web Service platform must adopt a set of protocols. Any platform has its data representation method and type system. To achieve interoperability, the Web Service platform must provide a standard type system for communicating different type systems in different platforms, programming languages, and component models. These protocols are:

1, XML and XSD

XML is a markup language used to mark electronic documents to make them structural, and is the basic format for representing data in the Web Service platform. In addition to being easy to create and analyze, the main advantage of XML is that it is both platform-independent and vendor-independent. XML follows the grammatical requirements of the W3C specification, separates form and content, has good self-description, is easy to expand, and has a wealth of third-party development libraries, making it very suitable for information transmission between systems of different architectures. As the application of XML becomes more and more widespread, XML has become the de facto data exchange standard due to its advantages in many application scenarios. XML was created by the World Wide Web Consortium (W3C). The XML SchemaXSD developed by the W3C defines a set of standard data types and provides a language to extend this set of data types.
The Web Service platform uses XSD as the data type system. When you use a language such as VB. NET or C# to construct a Web Service, in order to comply with the Web Service standard, all data types you use must be converted to XSD types. If you want it to be delivered between different organizations on different platforms and different software, you also need to wrap it in something. This thing is a protocol, like SOAP.

2. SOAP

SOAP is the Simple Object Access Protocol, which is a lightweight protocol for exchanging XML (a subset of the Standard Universal Markup Language) encoded information. Level protocol, capable of exchanging structured data between different information systems, is a mainstream implementation form of Web Service. It has three main aspects: the XML-envelope defines a framework for describing information content and how to process the content, rules for encoding program objects into XML objects, and conventions for implementing remote procedure calls (RPC). SOAP can run over any other transport protocol.

SOAP defines a framework based on the HTTP protocol that describes what is in the message, who sent it, who should accept and process it, and how to process them. It standardizes data formats by defining SOAP envelopes (Envelops), encapsulates XML data in envelopes for information exchange, and enables interoperability between heterogeneous systems.
Web Service hopes to realize that different systems can call each other through "software-software dialogue", breaking the incompatibility between software applications, websites and various devices, and achieving "seamless integration based on the Web" The goal.

3. WSDL

Web Service Description Language WSDL is a formal description document provided in a machine-readable manner and is based on XML (a subset of the Standard Generalized Markup Language). Used to describe Web Services and their functions, parameters and return values. Because it is based on XML, WSDL is both machine-readable and human-readable.

4. UDDI

The purpose of UDDI is to establish standards for e-commerce; UDDI is a set of Web-based, distributed, information registration center implementation standards for Web Service , and also includes a set of implementation standards for access protocols that enable enterprises to register the Web Services they provide so that other enterprises can discover them.

5. Calling RPC and messaging

Web Service itself actually implements communication between applications. We can use two ways to achieve communication between applications: remote procedure calls (RPC) and message passing. When using RPC, the concept of a client is to call a remote procedure on the server, usually by instantiating a remote object and calling its methods and properties. The RPC system attempts to achieve a kind of positional transparency: the server exposes the interface of the remote object, and the client acts as if the interface of these objects are used locally. This hides the underlying information and the client does not need it at all. Know which machine the object is on.

3. Webservice application scenarios and disadvantages

1. Webservice application scenarios

Strength 1: Cross-firewall communication
If the application has With thousands of users distributed around the world, communication between clients and servers will be a thorny problem. Because there is usually a firewall or proxy server between the client and the server. In this case, using DCOM is not that simple, and it is usually not convenient to publish the client program to such a large number of users. The traditional approach is to choose to use the browser as the client, write a lot of ASP pages, and expose the middle layer of the application to the end user. The result of this is that development is difficult and the program is difficult to maintain.

If the middle-tier component is replaced by WebService, the middle-tier component can be called directly from the user interface, thereby eliminating the step of creating an ASP page. To call WebService, you can directly use a SOAP client such as MicrosoftSOAP Toolkit or .NET, or you can use a self-developed SOAP client and then connect it to the application. Not only does it shorten the development cycle, it also reduces code complexity and enhances the maintainability of the application. The application does not need to navigate to the corresponding "result page" each time it calls a middle-tier component.

Enterprise-level application developers all know that enterprises often have to integrate various programs written in different languages ​​and running on different platforms, and this integration will cost a lot of development time. strength. Applications often need to obtain data from programs running on the IBM mainframe; or send data to the mainframe or UNIX applications. Various software often need to be integrated on the same platform, even if they come from different software vendors. Other applications can use standard methods to access the functionality and data exposed through the WebService.

Strength 2: Application Integration
Enterprise-level application developers all know that enterprises often have to integrate applications written in different languages ​​​​and run on different platforms. Various programs are integrated, and this integration will cost a lot of development effort. Applications often need to obtain data from programs running on the IBM mainframe; or send data to the mainframe or UNIX applications. Various software often need to be integrated on the same platform, even if they come from different software vendors. Other applications can use standard methods to access the functionality and data exposed through the WebService.

For example, there is an order login program for logging in new orders from customers, including customer information, shipping address, quantity, price, payment method, etc.; there is also an order execution program for Management of actual shipment of goods. The two programs are from different software vendors. When a new order arrives, the order entry program will notify the order execution program to send the goods. By adding a layer of WebService on top of the order execution program, the order execution program can "expose" the "AddOrder" function. In this way, whenever a new order arrives, the order login program can call this function to send the goods.

Strength 3: B2B integration
Using WebService to integrate applications can make the company's internal business processing more automated. But what happens when transactions span suppliers and customers, pushing the boundaries of the company? The integration of business transactions across companies is often called B2B integration.

WebService is the key to successful B2B integration. Through WebService, companies can "expose" key business applications to designated suppliers and customers. For example, by "exposing" the electronic ordering system and electronic invoicing system, customers can send orders electronically, and suppliers can send raw material purchase invoices electronically. Of course, this is not a new concept, EDI (Electronic Document Interchange) has been like this for a long time. However, the implementation of WebService is much simpler than EDI, and WebService runs on the Internet and can be easily implemented anywhere in the world, so its operating cost is relatively low. However, WebService is not a complete solution for document exchange or B2B integration like EDI. To achieve integration, in addition to WebService, many other components are required.

The biggest advantage of using WebService to implement B2B integration is that interoperability can be easily achieved. As long as the business logic is "exposed" and becomes a WebService, any designated partner can call these business logic, regardless of what platform their system runs on or what development language they use. This greatly reduces the time and cost spent on B2B integration, allowing many small and medium-sized enterprises that cannot afford EDI to achieve B2B integration.
Software and Data Reuse

"Software reuse is a significant topic with many forms and varying degrees of implementation.". The most basic form is source code module or class level reuse, and the other form is binary form component reuse.

Currently, reusable software components such as table controls or user interface controls occupy a large share of the market. Reuse of this type of software is very restrictive because it is limited to code and data cannot be reused. The reason is that it is easier to publish components and even source code, but it is not so easy to publish data, unless it is static data that does not change frequently.

While reusing code, webService can also reuse the code behind the data. Using WebService, you no longer have to purchase and install software components from a third party as before, and then call these components from the application; you only need to directly call the remote WebService. For example, to confirm the address entered by the user in the application, you only need to send the address directly to the corresponding WebService. This WebService will help you check the street address, city, province, zip code and other information to confirm the address. Is it in the corresponding postal code area? The provider of WebService can charge for the service based on time or number of uses. It is impossible to implement such a service through component reuse. In that case, you must download and install a database containing information such as street addresses, cities, provinces, and postal codes, and this database cannot be updated in real time.

Another situation of software reuse is to integrate the functions of several applications. For example, you want to build a portal application on the LAN so that users can check FedEx packages, check stock market conditions, manage their own schedules, and buy movie tickets online. There are many application vendors on the Web now, all of which have implemented these functions in their applications. Once they "expose" these functions through WebService, they can easily integrate all these functions into your portal site and provide users with a unified and friendly interface.

In the future, many applications will use WebService to extend the current component-based application structure into a component/WebService hybrid structure. You can use the functions provided by third-party WebService in the application, or you can add your own The application functionality is provided to others through WebService. In both cases, the code and the data behind the code can be reused.

2. Disadvantages of webservice

Disadvantage 1: Stand-alone application

Currently, enterprises and individuals still use many desktop applications. Some of them only need to communicate with other programs on the machine. In this case it is better to use local API and avoid using WebService. COM is ideal for working in this situation because it is small and fast. The same goes for server software running on the same server. It is best to use COM or other local APIs directly to make calls between applications. Although WebService is also suitable for these scenarios, it will consume a lot of resources and will not achieve any substantial benefits.

Weakness 2: Isomorphic applications in LAN
In many applications, all programs are developed with VB or VC, and all use COM under the windows platform. running on the same LAN. For example, there are two server applications that need to communicate with each other, or there is a Win32 or WinForm client program that wants to connect to another server program on the LAN. In these programs, using DCOM will be much more efficient than SOAP/http. Similarly, if a .NET program wants to connect to another .NET program on the LAN, .NET remoting should be used. Interestingly, in .NET remoting, you can also specify to use SOAP/http to make WebService calls. However, it is better to make RPC calls directly through TCP, which is much more efficient.

In short, as long as there are other methods that are more effective and feasible than WebService from the perspective of application structure, then don't use WebService.

4. Webservice code example

Realize interface mobilization between different projects and transfer object data through webservice~

Server-side project code

1. pom

<!--webservice-->
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web-services</artifactId>
 </dependency>
 <dependency>
     <groupId>org.apache.cxf</groupId>
     <artifactId>cxf-rt-frontend-jaxws</artifactId>
     <version>3.1.12</version>
 </dependency>
 <dependency>
     <groupId>org.apache.cxf</groupId>
     <artifactId>cxf-rt-transports-http</artifactId>
     <version>3.1.12</version>
 </dependency>
Copy after login

2. config configuration class

package com.guor.config;

import com.guor.service;
import com.guor.service.implImpl;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.xml.ws.Endpoint;

@Configuration
public class CxfConfig {

    @Bean
    public ServletRegistrationBean createServletRegistrationBean() {
        return new ServletRegistrationBean(new CXFServlet(), "/WebService/*");
    }

    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus() {
        return new SpringBus();
    }

    @Bean
    public WebService myService() {
        return new WebServiceImpl();
    }

    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(springBus(), myService());
        endpoint.publish("/api");
        return endpoint;
    }

}
Copy after login

3. Interface

package com.guor.service;

import com.guor.entity.dto.User;

import javax.jws;

@WebService(name = "WebService", // 暴露服务名称
        targetNamespace = "http://service.guor.com"// 命名空间,一般是接口的包名倒序
)
public interface WebService {

    User sendInfo(User user);
}
Copy after login
Copy after login
package com.guor.service.impl;

import com.guor.entity.dto.User;
import com.guor.service;
import org.springframework.stereotype.Service;

import javax.jws;


@WebService(serviceName = "WebService", // 与接口中指定的服务name一致
        targetNamespace = "http://service.guor.com", // 与接口中的命名空间一致,一般是接口的包名倒
        endpointInterface = "com.guor.service"// 接口地址
)
@Service
public class WebServiceImpl implements WebService {

    @Override
    public User sendInfo(User user) {
        return user;
    }
}
Copy after login

Client project code:

1. Create an identical interface

package com.guor.service;

import com.guor.entity.dto.User;

import javax.jws;

@WebService(name = "WebService", // 暴露服务名称
        targetNamespace = "http://service.guor.com"// 命名空间,一般是接口的包名倒序
)
public interface WebService {

    User sendInfo(User user);
}
Copy after login
Copy after login

2, webservice tool class

 /**
     * webservice接口地址
     */
    private static String address = "http://10.4.66.7:9992/MyProject/WebService/api?wsdl";

    /**
     * 通过webservice发送EC企业信息
     * @param User
     * @return
     */
    public static User sendInfo(User user) {
        try {
            // 代理工厂
            JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
            // 设置代理地址
            jaxWsProxyFactoryBean.setAddress(address);
            //添加用户名密码拦截器
            //jaxWsProxyFactoryBean.getOutInterceptors().add(new LoginInterceptor("root","admin"));;
            // 设置接口类型
            jaxWsProxyFactoryBean.setServiceClass(class);
            // 创建一个代理接口实现
            WebService service = (WebService) jaxWsProxyFactoryBean.create();

            return service.sendInfo(user);
        } catch (Exception e) {
            return null;
        }
    }
Copy after login

The above is the detailed content of How webservice implements interface calling and object transfer between springboot projects. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!