Table of Contents
1. Overview
2.REST application
3 . Front-End Application
Foo Details
4. Run the test
5. Customized Zuul filter
6. Testing Custom Zuul Filters
7. Conclusion
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)

Sep 11, 2018 pm 02:12 PM
spring cloud

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 id="Foo-nbsp-Details">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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Cleverly use Spring Cloud to solve load balancing problems under microservice architecture Cleverly use Spring Cloud to solve load balancing problems under microservice architecture Jun 23, 2023 pm 01:40 PM

As the complexity of enterprise applications continues to increase, more and more enterprises are beginning to split applications into multiple microservices and complete the entire business process through collaboration between microservices. This architectural approach can make applications more stable and scalable, but it also brings some new problems, such as load balancing, service discovery, etc. This article will introduce how to use Spring Cloud to solve the load balancing problem under the microservice architecture. What is load balancing? Load Balancing (LoadBalancing) refers to the balancing of multiple servers and networks

Spring Cloud source code analysis: Part 1 Spring Cloud source code analysis: Part 1 Aug 15, 2023 pm 04:04 PM

Personally, I think the prerequisite for reading the source code is that you must be able to use it. Once you are familiar with it, you can guess how others implemented it. If there are relevant official documents, then read the official documents.

Service-oriented Spring Cloud microservice development Service-oriented Spring Cloud microservice development Jun 23, 2023 pm 12:30 PM

With the development of the Internet and the continuous updating of technology, traditional single applications can no longer meet user needs, and the concept of microservices has emerged. SpringCloud is a microservice development toolkit launched by Pivotal. It provides developers with an extremely convenient way to build, deploy and manage microservice architecture applications. This article will introduce the service-oriented SpringCloud microservice development in detail, including the concept and architecture of SpringCloud, the microservice development process and

How to use Java to develop a container orchestration application based on Spring Cloud Kubernetes How to use Java to develop a container orchestration application based on Spring Cloud Kubernetes Sep 20, 2023 am 11:15 AM

How to use Java to develop a container orchestration application based on Spring Cloud Kubernetes. With the development and widespread application of container technology, container orchestration tools have become an indispensable part of developers. As one of the most popular container orchestration tools, Kubernetes has become the industry standard. In this context, combining Spring Cloud and Kubernetes, we can easily develop applications based on container orchestration. This article will introduce in detail

Spring Cloud microservice architecture deployment and operation Spring Cloud microservice architecture deployment and operation Jun 23, 2023 am 08:19 AM

With the rapid development of the Internet, the complexity of enterprise-level applications is increasing day by day. In response to this situation, the microservice architecture came into being. With its modularity, independent deployment, and high scalability, it has become the first choice for enterprise-level application development today. As an excellent microservice architecture, Spring Cloud has shown great advantages in practical applications. This article will introduce the deployment and operation and maintenance of SpringCloud microservice architecture. 1. Deploy SpringCloud microservice architecture SpringCloud

Introduction to Spring Cloud framework in Java language Introduction to Spring Cloud framework in Java language Jun 09, 2023 pm 10:54 PM

Introduction to the Spring Cloud framework in the Java language With the popularity of cloud computing and microservices, the Spring Cloud framework has become one of the preferred frameworks for building cloud native applications in the Java language. This article will introduce the concepts and features of the Spring Cloud framework, and how to use Spring Cloud to build a microservice architecture. Introduction to SpringCloud The SpringCloud framework is a microservice framework based on SpringBoot. it is

Spring Cloud microservice practice for implementing distributed locks Spring Cloud microservice practice for implementing distributed locks Jun 22, 2023 pm 11:28 PM

With the popularity of microservice architecture, more and more enterprise development teams are beginning to use Spring Cloud to build their own microservice systems. In a distributed environment, implementing distributed locks is an important technical challenge. This article will introduce how to implement microservice practices of distributed locks under the Spring Cloud framework. First, we need to understand what a distributed lock is. Distributed lock is a technology used to protect access to shared resources. It can ensure that in a distributed environment, multiple nodes will not modify the same resource at the same time or

The combination of Spring Cloud microservices and componentization The combination of Spring Cloud microservices and componentization Jun 23, 2023 am 10:21 AM

With the continuous development of Internet technology, more and more enterprises are beginning to adopt microservice architecture to build their systems. SpringCloud is a microservices framework that has emerged rapidly in this context. On this basis, this article will discuss the combination of SpringCloud microservices and componentization, and analyze its advantages and implementation methods. 1. Introduction to SpringCloud microservices SpringCloud is an upgraded version of the SpringBoot project. It provides a large number of tools.

See all articles