


Implementation of using Spring Cloud Netflix Zuul proxy gateway to access backend REST services (code)
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
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 }
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 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>
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
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('myApp', ["ngResource"]); app.controller('mainCtrl', function($scope,$resource,$http) { $scope.foo = {id:0 , name:"sample foo"}; $scope.foos = $resource("/foos/:fooId",{fooId:'@id'}); $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>
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); } }
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.
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; } // ...}
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)); } }
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")); }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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.

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. 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

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 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

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

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.
