Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Learn from me Spring Cloud (Finchley version)-02-build distributed applications

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

As mentioned in the previous section (learn from me Spring Cloud (Finchley version)-01-opening), Spring Cloud is a toolset for quickly building distributed applications. In this section, we will write a simple distributed application and explore the problems with this distributed application.

Service consumer & provider

This book uses service providers and service consumers to describe the invocation relationship between microservices. The following table explains service providers and service consumers.

Table-Service providers and Service consumers

The noun defines the callee of the service provider service (that is, the service providing services for other services) the caller of the service consumer service (that is, services that depend on other services)

Take the movie ticketing system as an example. In the picture, the user initiates a ticket purchase request to the movie microservice. Before the ticket purchase business operation, the movie microservice needs to call the interface of the user microservice to query the current user's balance and whether it meets the ticket purchase criteria. In this scenario, the user microservice is a service provider and the movie microservice is a service consumer.

Around this scenario, first write a user micro-service, and then write a movie micro-service.

TIPS

Service consumers and service providers describe only the invocation relationship between micro-services, which generally appear in pairs. For example, in this paper, the user micro-service is the service provider of the movie micro-service, and the movie micro-service is the service consumer of the user micro-service. When many beginners communicate with the author, they will describe how the provider …... It is not true that consumers and providers are inherent attributes of microservices-for example, if A calls BMagne B calls C, then B is the provider relative to A, and B is the consumer relative to C.

Spring Boot/Spring Cloud application development routines

After the era of Spring Boot/Spring Cloud, application development basically follows the following three axes:

Add dependencies and annotations to write configuration

As for your business code, how to write it and how to write it.

TIPS

For lazy people, you can use Spring Initilizr (integrated on IDEA, Spring Tool Suite and other IDE, or web version on http://start.spring.io) to create applications, which will generate project dependencies and project skeletons for you. In the follow-up, the author will update the relevant tutorials in an extra form.

Write service provider [user microservice]

Create a Maven project that relies on the following:

4.0.0com.itmuch.cloudmicroservice-simple-provider-user0.0.1-SNAPSHOTjar org.springframework.boot spring-boot-starter-parent 2.0.7.RELEASE UTF-8 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-jpa com.h3database h3 org.projectlombok lombok true org.springframework.cloud spring-cloud-dependencies Finchley .SR2 pom import org.springframework.boot spring-boot-maven-plugin

Among them, spring-boot-starter-web provides support for Spring MVC; spring-boot-starter-data-jpa provides support for Spring Data JPA; H3 is an embedded database with syntax similar to MySQL (I really have no incentive to write a lot of content to demonstrate how to install MySQL database for a simple demonstration); lombok is a development tool that can help you simplify N multi-redundant code.

WARNING

Before Lombok, you must install the Lombok plug-in for your IDE! Please refer to:

TIPS

Lombok Quick start: Lombok official website:

Create an entity class:

@ Entity@Data@NoArgsConstructor@AllArgsConstructorpublic class User {@ Id@GeneratedValue (strategy = GenerationType.AUTO) private Long id;@Columnprivate String username;@Columnprivate String name;@Columnprivate Integer age;@Columnprivate BigDecimal balance;}

Create a DAO:

@ Repositorypublic interface UserRepository extends JpaRepository {}

Create a Controller:

@ RequestMapping ("/ users") @ RestControllerpublic class UserController {@ Autowiredprivate UserRepository userRepository;@GetMapping ("/ {id}") public Optional findById (@ PathVariable Long id) {return this.userRepository.findById (id);}}

Among them, @ GetMapping is a new annotation provided by Spring 4.3. It is a composite annotation equivalent to @ RequestMapping (method = RequestMethod.GET) to simplify development. Similarly, there are @ PostMapping, @ PutMapping, @ DeleteMapping, @ PatchMapping and so on.

Write the startup class:

@ SpringBootApplicationpublic class ProviderUserApplication {public static void main (String [] args) {SpringApplication.run (ProviderUserApplication.class, args) } / * * initialize user information * Note: Spring Boot2 cannot initialize the SQL script with spring.datasource.schema/data as specified by 1.x Otherwise, it cannot coexist with actuator * for more information: * https://github.com/spring-projects/spring-boot/issues/13042 * https://github.com/spring-projects/spring-boot/issues/13539 * * @ param repository repo * @ return runner * / @ BeanApplicationRunner init (UserRepository repository) {return args-> {User user1 = new User (1L, "account1", "Zhang San", 20, new BigDecimal (100.00)) User user2 = new User (2L, "account2", "Li Si", 28, new BigDecimal (180.00)); User user3 = new User (3L, "account3", "Wang Wu", 32, new BigDecimal (280.00)); Stream.of (user1, user2, user3) .forEach (repository::save);};}}

@ SpringBootApplication is a combined annotation that integrates @ Configuration, @ EnableAutoConfiguration, and @ ComponentScan annotations, and enables component scanning and autoconfiguration of the SpringBoot program. In the process of developing SpringBoot programs, annotations such as @ Configuration, @ EnableAutoConfiguration, and @ ComponentScan are often combined, so SpringBoot provides @ SpringBootApplication to simplify development.

At startup, we use ApplicationRunner init (UserRepository repository) to initialize three pieces of data, namely, Zhang San, Li Si, and Wang Wu. @ Bean is a method annotation that instantiates a Bean and names it with the name of the method. Similar to the way XML is configured.

Write the configuration file application.yml:

Server:# specifies Tomcat port port: 8000spring:jpa: # Let hibernate print SQL show-sql: truelogging:level: root: INFO # configure log level, let hibernate print out the SQL parameter org.hibernate: INFO org.hibernate.type.descriptor.sql.BasicBinder: TRACE org.hibernate.type.descriptor.sql.BasicExtractor: TRACE

In the development of traditional Web applications, properties format files are often used as configuration files. Spring Boot and Spring Cloud support using files in properties or yml format as configuration files.

The yml file format is written by YAML (Yet Another Markup Language). Files in YAML and properties format can be converted into each other. For example, application.yml in this section is equivalent to the following properties file:

Server.port=8000spring.jpa.show-sql=truelogging.level.root=INFOlogging.level.org.hibernate=INFOlogging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACElogging.level.org.hibernate.type.descriptor.sql.BasicExtractor=TRACE

It is not difficult to see that YAML has a clearer structure than properties; it is also more readable and maintainable, and the syntax is very concise. Therefore, this book uses the YAML format as the configuration file. However, yml has strict indentation, and the use between key and value: separation, the space after the colon can not be less, please note.

test

Visit http://localhost:8000/users/1 to get the results:

{"id": 1, "username": "account1", "name": "Zhang San", "age": 20, "balance": 100.00} Writing service consumers [movie microservices]

We have written a service provider (user microservice) and this section will write a service consumer (movie microservice). The service is very simple and uses RestTemplate to invoke the API of the user microservice to query the user information for the specified id.

Create a Maven project, ArtifactId is microservice-simple-consumer-movie.

Add dependence:

Org.springframework.bootspring-boot-starter-web

Create an entity class:

@ Data@AllArgsConstructor@NoArgsConstructorpublic class User {private Long id;private String username;private String name;private Integer age;private BigDecimal balance;}

Create a startup class:

@ SpringBootApplicationpublic class ConsumerMovieApplication {@ Beanpublic RestTemplate restTemplate () {return new RestTemplate ();} public static void main (String [] args) {SpringApplication.run (ConsumerMovieApplication.class, args);}}

Create a Controller:

@ RequestMapping ("/ movies") @ RestControllerpublic class MovieController {@ Autowiredprivate RestTemplate restTemplate;@GetMapping ("/ users/ {id}") public User findById (@ PathVariable Long id) {/ / the placeholder capability of RestTemplate User user = this.restTemplate.getForObject ("http://localhost:8000/users/{id}", User.class, id); / /. The business of film microservices. Return user;}}

As you can see from the code, Controller uses RestTemplate to invoke the RESTful API of the user's microservice.

Write the configuration file application.yml:

Server:port: 8010

Expand reading

In this paper, RestTemplate is used to implement remote calls based on HTTP. In fact, starting with Spring 5, WebFlux provides Web Client:WebClinet for Reactive, which is basically similar to RestTemplate, but with better performance and better throughput. Those who are interested can go to learn about it. Here, the author has done some simple encapsulation of WebClient, you can also pay attention to:

test

Visit: http://localhost:8010/movies/users/1, and the results are as follows:

{"id": 1, "username": "account1", "name": "Zhang San", "age": 20, "balance": 100.00} problems

So far, we have implemented the simplest distributed application, which communicates with each other through HTTP. The code is very simple, but there are several problems with this simple code:

The app has no monitoring, no drawing board, and no indicators. In this era when Growth Hack is gradually becoming mainstream, how dare you come out and hang out without a Dashboard to visualize the system pressure, QPS, CPU, memory, and the number of daily active users?

Address hard-coding problem-the address of the user's microservice is written to death in the movie microservice. If the user's microservice address changes, do you want to go back to the movie microservice?

You may question why the user's microservice address has changed, just keep it the same, it's not a problem. Here are two examples:

Example 1: if you use Docker, the address will change almost every time you start.

Example 2: you used TXYun before, but then you want to migrate user microservices to Aliyun. At this point, IP will change. I'm sure you won't be happy to find out which services call the interface of the user's microservice, and then all the services that invoke the user's microservice change the address.

How to consider load balancing? Is it necessary to add a NGINX between the movie microservice and the user microservice to do load balancing? It sounds feasible, but if there are 10,000 + services (it's no exaggeration, the number of our microservices is this number multiplied by NMagi N > = m, ), how complicated is the configuration of this NGINX?

There is no fault tolerance mechanism between services, and I believe you who are passionate about technology have heard the words fault tolerance, downgrade, fallback, fallback and so on more than once.

If the application fails, how can you find the problem quickly?

What about user authentication and authorization? Was it eaten by a dog?

You may or may not understand the above words. It doesn't matter, please continue to read, the author will use popular language to describe, after you read this series, you will know that those so-called high-end theory, terminology, technology, it turns out that is what it is.

Matching code GitHub: https://github.com/eacdy/spring-cloud-study/tree/master/2018-Finchley/microservice-simple-provider-userhttps://github.com/eacdy/spring-cloud-study/tree/master/2018-Finchley/microservice-simple-consumer-movieGitee: https://gitee.com/itmuch/spring-cloud-study/tree/master/2018-Finchley/microservice-simple-provider-userhttps://gitee.com/itmuch/spring-cloud-study/tree/master/2018-Finchley/microservice-simple-consumer-movie

Original: http://www.itmuch.com/spring-cloud/finchley-2/ reproduced, please state the source.

Practical information sharing

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report