Home > Java > javaTutorial > Implementation of using Spring Cloud Netflix Zuul proxy gateway to access backend REST services (code)

Implementation of using Spring Cloud Netflix Zuul proxy gateway to access backend REST services (code)

不言
Release: 2018-09-11 14:12:25
Original
2342 people have browsed it

The content this article brings to you is about the implementation (code) of using Spring Cloud Netflix Zuul proxy gateway to access the backend REST service. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

1. Overview

In this article, we will explore how to communicate between a front-end application and a back-end REST API service that are deployed separately from each other. The purpose is to solve the browser's cross-domain resource access and same-origin policy restrictions, allowing the page UI to call the background API even if they are not in the same server.

We have created two separate applications here - a UI application and a simple REST API, and we will use Zuul proxy in the UI application to proxy calls to the REST API. Zuul is Netflix's JVM-based router and server-side load balancer. Spring Cloud has great integration with embedded Zuul proxy.

2.REST application

Our REST API application is a simple Spring Boot application. In this article, the API deployed in the server will be run on port 8081.

Configuration File

server.contextPath=/spring-zuul-foos-resourceserver.port=80
81
Copy after login

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

public class Foo {
    private long id;    
    private String name;    
    // standard getters and setters
    }
Copy after login

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));
    }
}
Copy after login

3 . Front-End Application

Our UI application is also a simple Spring Boot application. In this article the application is running on port 8080.

First we need to add dependency for zuul support via Spring Cloud to our UI application's pom.xml:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId></dependency>
Copy after login

Next - We need to configure Zuul since 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
Copy after login

NOTE:

  • We proxy our resource server Foos.

  • All requests starting with "/foos/" from the UI will be routed to our Foos resource server at: http://loclahost:8081/spring-zuul- foos-resource/foos/

Then write our main page index.html — using some AngularJS here:

<html>
<body ng-app="myApp" ng-controller="mainCtrl">
<script src="angular.min.js"></script>
<script src="angular-resource.min.js"></script>
<script>
var app = angular.module(&#39;myApp&#39;, ["ngResource"]);

app.controller(&#39;mainCtrl&#39;, function($scope,$resource,$http) {
    $scope.foo = {id:0 , name:"sample foo"};
    $scope.foos = $resource("/foos/:fooId",{fooId:&#39;@id&#39;});

    $scope.getFoo = function(){
        $scope.foo = $scope.foos.get({fooId:$scope.foo.id});
    }  
});</script><p>
    <h1>Foo Details</h1>
    <span>{{foo.id}}</span>
    <span>{{foo.name}}</span>
    <a href="#" ng-click="getFoo()">New Foo</a>
    </p>
    </body>
    </html>
Copy after login

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

Finally, the Boot-enabled application:

@EnableZuulProxy@SpringBootApplicationpublic class UiApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(UiApplication.class, args);
    }
}
Copy after login

The @EnableZuulProxy annotation is used here to start the Zuul proxy, which is very clean and concise.

4. Run the test

Start 2 application systems respectively, enter http://localhost:8080/index in the browser
Visit each time you click the "New Foo" button Backend REST API once.
Implementation of using Spring Cloud Netflix Zuul proxy gateway to access backend REST services (code)

5. Customized Zuul filter

There are multiple Zuul filters available, we can also create our own custom filter:

@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;
    }    // ...}
Copy after login

This A simple filter just adds an attribute called "Test" to the request header - of course, we can add more to our request as needed.

6. Testing Custom Zuul Filters

Finally, let’s test to make sure our custom filter is working - 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));
    }
}
Copy after login

Now - Let’s test it out:

@Testpublic void whenSendRequest_thenHeaderAdded() {    
Response response = RestAssured.get("http://localhost:8080/foos/1");

    assertEquals(200, response.getStatusCode());
    assertEquals("TestSample", response.getHeader("Test"));
}
Copy after login

7. Conclusion

In this post, we focused on routing requests from UI application to REST using Zuul API. We successfully solved the CORS and Same Origin Policy, and we also managed to customize and augment the HTTP requests in transit.

Related recommendations:

spring cloud's Feign uses HTTP to request remote services

##spring-cloud-sleuth zipkin tracking service Implementation (2)

The above is the detailed content of Implementation of using Spring Cloud Netflix Zuul proxy gateway to access backend REST services (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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