Access to the backend Rest service implementation using the spring Cloud Netflix Zuul Proxy Gateway (code)

Source: Internet
Author: User
This article brings you to the content of the use of spring Cloud Netflix Zuul Proxy gateway access to the backend Rest service Implementation (code), there is a certain reference value, the need for friends can refer to, I hope to help you.

1. Overview

In this article, we'll explore how to communicate between front-end applications and back-end REST API services that are deployed separately from each other. The goal is to address browser cross-domain resource access and the same-origin policy restrictions, allowing the page UI to invoke APIs in the background, even if they are not on the same server.

We created two separate applications here-a UI application and a simple rest API, and we'll use the Zuul proxy in our UI application to proxy calls to the rest API. Zuul is a JVM-based router and server-side load balancer for Netflix. Spring Cloud is well integrated with embedded Zuul agents.

2.REST applications

Our Rest API application is a simple spring boot application. In this article, you will run the API deployed on port 8081 on the server.

Configuration file

server.contextpath=/spring-zuul-foos-resourceserver.port=8081

Let's first define the basic DTO for the resource we will use:

public class Foo {    private long ID;        private String name;        Standard getters and Setters    }

Define a simple controller:

@Controllerpublic class Foocontroller {    @RequestMapping (method = requestmethod.get, value = "/foos/{id}")        @ Responsebody public    Foo FindByID (      @PathVariable long ID, httpservletrequest req, httpservletresponse Res) {              return new Foo (Long.parselong (Randomnumeric (2)), Randomalphabetic (4));}    }

3. Front-end applications

Our UI application is also a simple spring boot application. In this article, the app runs on port 8080.

First, we need to add a dependency on Zuul support to the pom.xml of our UI application through Spring cloud:

<dependency>    <groupId>org.springframework.cloud</groupId>    <artifactId> Spring-cloud-starter-netflix-zuul</artifactid></dependency>

Next-we need to configure Zuul because we are using spring Boot, so we will do this in APPLICATION.YML:

Zuul:  routes:    foos:      path:/foos/**      Url:http://localhost:8081/spring-zuul-foos-resource/foos

Attention:

    • We represent our resource server Foos.

    • All requests from the UI that begin with "/Foos/" will be routed to our Foos resource server with the address:///Loclahost:8081/spring-zuul-foos-resource/foos/

Then write our main page index.html-here to use some angularjs:


The most important aspect here is how we use relative URLs to access the API!
Keep in mind that the API application is not deployed on the same server as the UI application, so the relative URL does not work and does not work without a proxy.
However, through proxies, we access foo resources through the Zuul proxy, which is configured to route these requests to the location of the actual deployment API.

Finally, the boot-enabled application:

@EnableZuulProxy @springbootapplicationpublic class UIApplication extends Springbootservletinitializer {public    static void Main (string[] args) {        springapplication.run (uiapplication.class, args);}    }

The @enablezuulproxy annotations are used here to start the Zuul agent, which is very clean and concise.

4. Run the test

Launch 2 applications Separately, enter Http://localhost:8080/index in the browser
Access the backend Rest API once per click on the "New Foo" button.

5. Custom Zuul Filter

With multiple Zuul filters available, we can also create our own custom filters:

@Componentpublic class Customzuulfilter extends Zuulfilter {    @Override public    Object run () {        RequestContext CTX = Requestcontext.getcurrentcontext ();        Ctx.addzuulrequestheader ("Test", "testsample");                return null;    }    @Override Public    Boolean shouldfilter () {           return true;    }    // ...}

This simple filter simply adds a property named "Test" to the request header-we can, of course, increase our request as needed.

6. Test the Custom Zuul filter

Finally, let's test to make sure our custom filters work properly-first we'll modify our Foocontroller on the Foos resource server:

@Controllerpublic class Foocontroller {    @GetMapping ("/foos/{id}")    @ResponseBody public    Foo FindByID (      @PathVariable Long ID, httpservletrequest req, httpservletresponse Res) {              if (Req.getheader ("test") = null) {            res.addheader ("Test", Req.getheader ("Test"));        }        return new Foo (Long.parselong (Randomnumeric (2)), Randomalphabetic (4));}    }

Now-let's test it:

@Testpublic void whensendrequest_thenheaderadded () {    Response Response = Restassured.get ("http://localhost:8080/ Foos/1 ");    Assertequals (Response.getstatuscode ());    Assertequals ("Testsample", Response.getheader ("Test"));

7. Conclusion

In this article, we focus on using Zuul to route requests from the UI application to the rest API. We have successfully solved the cors and homology strategy, and we have managed to customize and augment the HTTP requests in transit.

Related Article

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.