Traditional Java Web (non-spring Boot), non-Java language projects access to the spring cloud scenario

Source: Internet
Author: User

When the technology architecture transforms into spring cloud, there must be some older projects, and the code has become a heavenly book, and it is hoped that these traditional applications can be plugged into the spring cloud architecture as a service for other project calls without massive refactoring. We need to use native Eureka/ribbon to manually complete the registry and query the service list function. If you are a non-Java project, you can use the Spring Sidecar project to connect to spring Cloud to form heterogeneous systems.

Selection of JDK versions

It is strongly recommended that you use JDK8 because the latest version of Eureka Client has requested JDK8, and a run- No such method time error will occur for versions below JDK8. If you cannot use JDK8, you can select an earlier version of the Eureka client, but the minimum is only supported to JDK7. For older projects, there is no risk of upgrading the JDK without moving the code unless you are using a specific version of the JDK functionality. The biggest risk is actually upgrading the development framework (e.g. SPRING3 to Spring4).

Service List Query

The core issue for non-spring cloud to invoke a service interface within the cloud system is how to obtain the destination service address. We can directly use the native Eureka, the Ribbon Library to achieve this:

 PackageCom.dfs.pos.gateway.cloud;Importjava.io.IOException;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory; Public classServiceaddressselector {/*** The default ribbon configuration file name, which needs to be placed in the Classpath directory*/     Public Static FinalString ribbon_config_file_name = "Ribbon.properties"; Private Static FinalLogger log = Loggerfactory.getlogger (serviceaddressselector.class); Private StaticRoundrobinrule Chooserule =NewRoundrobinrule (); Static{log.info ("Start initializing Ribbon"); Try {            //loading Ribbon configuration Filesconfigurationmanager.loadpropertiesfromresources (ribbon_config_file_name); } Catch(IOException e) {e.printstacktrace (); Log.error ("Ribbon initialization Failed"); Throw NewIllegalStateException ("Ribbon initialization Failed"); }        //initializing the Eureka ClientDiscoverymanager.getinstance (). InitComponent (NewMydatacenterinstanceconfig (),Newdefaulteurekaclientconfig ()); Log.info ("Ribbon Initialization Complete"); }    /*** Select an address according to the polling policy * *@paramclientName * Prefix name of the configuration item in the Ribbon.properties configuration file, such as MyClient *@returnNULL indicates that the service does not currently have an address available*/     Public Staticalanserviceaddress SelectOne (String clientName) {//Clientfactory.getnamedloadbalancer caches the results, so don't worry about it launching queries to Eureka every time.Dynamicserverlistloadbalancer lb =(Dynamicserverlistloadbalancer) clientfactory. Getnamedloadbalancer (ClientName); Server selected= Chooserule.choose (LB,NULL); if(NULL==selected) {Log.warn ("Service {} No address available", ClientName); return NULL; } log.debug ("Service {} selection result: {}", ClientName, selected); return Newalanserviceaddress (Selected.getport (), Selected.gethost ()); }    /*** Select all available addresses for the service * *@paramClientName *@return     */     Public StaticList<alanserviceaddress>selectavailableservers (String clientName) {dynamicserverlistloadbalancer lb=(Dynamicserverlistloadbalancer) clientfactory. Getnamedloadbalancer (ClientName); List<Server> serverlist =lb.getreachableservers (); if(Serverlist.isempty ()) {Log.warn ("Service {} No address available", ClientName); returncollections.emptylist (); } log.debug ("Service {} All selection results: {}", ClientName, serverlist); returnServerlist.stream (). Map (Server-Newalanserviceaddress (Server.getport (), Server.gethost ())). Collect (Collectors.tolist ()); }}

The way to use it is simple:

// Select all available addresses for the myclient corresponding service list<alanserviceaddress> list = alanserviceaddressselector.selectavailableservers ("myclient"); SYSTEM.OUT.PRINTLN (list); // Select an available address (polling) for the myclient corresponding service, and return NULL to indicate that the service does not currently have an address available Alanserviceaddress addr = Alanserviceaddressselector.selectone ("myclient"); System.out.println (addr);

The

Then obtains the URL of the target service and can then send an HTTP request to complete the call in such a way as the HTTP client. Of course this is far from the convenience of using the feign component in the spring cloud system, but it's not much of an old project where the code has become a heavenly book. &NBSP
This class works as a prerequisite for providing a ribbon.properties file that specifies Eureka address and service name related information:

 s3# fixed notation, MyClient uses the Ribbon load Balancer myclient.ribbon.NIWSServerListClassName  = =60000  # controls whether to register itself to Eureka eureka.registration.enabled  = # Eureka related configuration Eureka.prefersamezone  = true  eureka.shouldusedns  =eureka.serviceurl.default  =http://x.x.x.x:8761 / eurekaeureka.decodername  =jacksonjson 

In addition, the DiscoveryManager.getInstance().initComponent() method has been marked @Deprecated , but the Ribbon's DiscoveryEnabledNIWSServerList component code still DiscoveryManager obtains the Eurekaclient object by:

Discoveryclient discoveryclient = discoverymanager.getinstance ()                . Getdiscoveryclient ();

Therefore, this can only be used in outdated methods, otherwise the ribbon will not get Eureka Client, the program does not run through.

Invoking the HTTP interface using native feign

If your old project is fortunate enough to be able to use feign, it can greatly simplify the HTTP invocation process. We can use native feign instead of HTTP Client. Define the feign interface first:

 Public Interface Clientidremoteservice {    @RequestLine ("Post/client/query")    @Headers ("Content-type: application/x-www-form-urlencoded ")    @Body (" Uuid={uuid} ")    String Getclientid (@Param (" UUID ") String uuid);

The following is the spring configuration class:

@Configuration Public classNoncloudfeignconfig {Private Static FinalLogger log = Loggerfactory.getlogger (noncloudfeignconfig.class); @AutowiredPrivateObjectfactorymessageconverters; @Bean PublicClientidremoteservice Clientidremoteservice () {Log.info ("Initialize feign interface to get UUID service"); returnFeign.builder (). Encoder (NewSpringencoder (messageconverters)). Decoder (NewSpringdecoder (messageconverters)). Target (Clientidremoteservice.class, "http://xxxx.com"); }}

In this case, you can pass the code

@Autowired Private  = Service.getclientid ("uuid");

The way it was called. For exception handling, you can customize the feign Errordecoder, and then pass your errordecoder in when calling Feign.builder ().
If the spring version of your project does not support annotation configuration, you can also manually place the feign proxy object into context programmatically.

Technical solutions for non-Java applications that access spring cloud

It is because all of the services in the spring Cloud Netflix architecture are exposed through the HTTP protocol, and with the language independence of HTTP, we have the possibility of incorporating old projects and even non-Java applications into the system. If a project that is implemented with node. JS wants to turn itself into a service for other services to invoke (or to call someone else's service), the options available are:

    • Spring Sidecar Project
      The principle is to start a node. js corresponding agent application sidecar, sidecar itself is implemented with spring cloud, will register itself in Eureka, this sidecar application logically represents the use of NODEJS implementation of services, And it also integrates the Ribbon, hystrix, Zuul these components. Other services when you call node. js, Eureka returns the address of Sidecar, so the request is sent to Sidecar,sidecar and the request is forwarded to node. js. When node. JS wants to invoke someone else's service, node. JS needs to send a request to Sidecar, and Sidecar sends an HTTP request for node. JS, and then returns the result to node. js.

    • HTTP interface for direct use of Eureka
      Since Eureka also exposes itself through the interface of the HTTP protocol, we can manually send HTTP requests in node. JS to implement the registration, query, and heartbeat capabilities of the service. Eureka Interface Description Information can be found on the official GitHub wiki.

Summarize

With the language-agnostic advantage of the HTTP protocol, we have the ability to access non-Java applications in the Spring Cloud architecture architecture. But the cost of performance is actually, after all, HTTP is a character-based protocol, and its parsing speed is not as good as the binary protocol. At the same time, the spring boot based on Tomcat and SPRINGMVC is also relatively bulky and cumbersome. But the popularity of spring boot in recent years suggests that the Java Web is moving in the direction of simplification and lightweighting, and may later eliminate the servlet container completely instead of using a communication framework such as Netty.

Transferred from: http://blog.csdn.net/neosmith/article/details/70049977

Traditional Java Web (non-spring Boot), non-Java language projects access to the spring cloud scenario

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.