With the development of cloud computing and the continuous expansion of enterprise business, microservice architecture has become a very popular system architecture. Among them, Spring Boot and Spring Cloud are currently the most commonly used microservice frameworks. Spring Cloud provides a wealth of components to support the development and management of microservices, including service registration and discovery, routing, load balancing, configuration management, circuit breakers, etc.
In this article, we will build a distributed and secure Spring Cloud microservice flying system as a case to demonstrate the powerful functions of Spring Cloud.
First, we need to register and discover services. Spring Cloud provides Eureka to help us realize service registration and discovery. We will complete the registration and discovery of services through Eureka Server.
Create Eureka Server application:
@SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
Configure in application.properties:
server.port=8761 eureka.client.register-with-eureka=false eureka.client.fetch-registry=false
In the service provider and service consumer applications, we need to register it to Eureka Server.
Configured in the application.properties of the service provider:
spring.application.name=flight-service-provider server.port=8080 eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
Configured in the application.properties of the service consumer:
spring.application.name=flight-service-consumer server.port=8081 eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
The service provider creates a RESTful interface through Spring MVC:
@RestController @RequestMapping("/flights") public class FlightController { @GetMapping("/{flightId}") public ResponseEntity<Flight> getFlight(@PathVariable Integer flightId) { Flight flight = new Flight(flightId, "Shanghai", "Beijing", new Date()); return new ResponseEntity<>(flight, HttpStatus.OK); } }
The service consumer calls the service through Spring RestTemplate:
@Service public class FlightService { @Autowired private RestTemplate restTemplate; @Value("${service.provider.url}") private String serviceProviderUrl; public Flight getFlight(Integer flightId) { return restTemplate.getForObject(serviceProviderUrl + "/flights/{flightId}", Flight.class, flightId); } }
Among them, service.provider.url is in the application Configure in application.properties of the program.
In actual applications, service providers are likely to be deployed on multiple instances. At this time, we need to perform load balancing to improve the system's performance. Performance and availability. Spring Cloud provides Ribbon to support load balancing.
Configure in the application.properties of the service consumer:
service.provider.url=http://flight-service-provider/ spring.cloud.loadbalancer.ribbon.enabled=true
Use the load-balanced RestTemplate in FlightService:
@Service public class FlightService { @Autowired @LoadBalanced private RestTemplate restTemplate; @Value("${service.provider.name}") private String serviceProviderName; public Flight getFlight(Integer flightId) { return restTemplate.getForObject("http://" + serviceProviderName + "/flights/{flightId}", Flight.class, flightId); } }
Among them, service.provider.name is in the application Configure in application.properties of the program.
Spring Cloud provides Config to easily manage application configuration. We can store the application configuration in a Git repository and distribute it through Config Server.
Create Config Server application:
@SpringBootApplication @EnableConfigServer public class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); } }
Configure in application.properties:
server.port=8888 spring.cloud.config.server.git.uri=https://github.com/xxx/xxx.git spring.cloud.config.server.git.search-paths=config-repo
In service providers and service consumers, we can obtain it through Config Server Application configuration.
Configure in the service provider's application.yml:
spring: application: name: flight-service-provider cloud: config: uri: http://localhost:8888 label: master profile: dev
Configure in the service consumer's application.yml:
spring: application: name: flight-service-consumer cloud: config: uri: http://localhost:8888 label: master profile: dev
In a microservice architecture, because the dependencies between services are very complex, downtime or problems in some services may cause the entire system to collapse. To deal with this situation, we can use circuit breakers to handle service degradation.
Spring Cloud provides Hystrix to support the circuit breaker function.
Configure in the application.yml of the service consumer:
spring: application: name: flight-service-consumer cloud: config: uri: http://localhost:8888 label: master profile: dev loadbalancer: ribbon: enabled: true circuitbreaker: enabled: true resilience4j: enabled: false circuitBreaker: backend: flight-service-provider failureRateThreshold: 50
Add @HystrixCommand annotation in FlightController:
@RestController @RequestMapping("/flights") public class FlightController { @Autowired private FlightService flightService; @GetMapping("/{flightId}") @HystrixCommand(fallbackMethod = "defaultGetFlight") public ResponseEntity<Flight> getFlight(@PathVariable Integer flightId) { Flight flight = flightService.getFlight(flightId); if (flight != null) { return new ResponseEntity<>(flight, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } public ResponseEntity<Flight> defaultGetFlight(Integer flightId) { return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } }
Among them, defaultGetFlight is the downgrade function.
In distributed systems, security issues are very important. Spring Cloud provides Security to support security management.
Add in the pom.xml of the service provider and service consumer applications:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-security</artifactId> </dependency>
Configure in the application.yml of the service provider and service consumer applications:
security: basic: enabled: true spring: security: user: name: user password: password
Among them, name and password are the user's name and password respectively. It should be noted that in actual applications, more secure methods must be used for user authentication and authorization management.
Add the @PreAuthorize annotation at the class level of FlightController:
@RestController @RequestMapping("/flights") @PreAuthorize("hasRole('ROLE_ADMIN')") public class FlightController { @Autowired private FlightService flightService; @GetMapping("/{flightId}") public ResponseEntity<Flight> getFlight(@PathVariable Integer flightId) { Flight flight = flightService.getFlight(flightId); if (flight != null) { return new ResponseEntity<>(flight, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } }
Among them, the @PreAuthorize annotation is used to perform security verification on FlightController. In actual applications, different security verifications can be performed on each method.
In this way, we have completed the construction of a distributed and secure Spring Cloud microservice flight system. Through the cases in this article, we can see that Spring Cloud provides a wealth of components to help us build microservices. At the same time, we also need to pay attention to some challenges brought by microservice architecture, such as service registration and discovery, inter-service communication, load balancing, configuration management, circuit breakers, security and other issues. In actual applications, we need to make technology selection and configuration based on specific scenarios.
The above is the detailed content of Build a distributed and secure Spring Cloud microservice flight system. For more information, please follow other related articles on the PHP Chinese website!