The SOA Foundation for Springcloud Learning

Source: Internet
Author: User
Tags aliyun

I. SOA Brief INTRODUCTION

A service-oriented architecture (SOA) is a component model that links different functional units (called services) of an application through well-defined interfaces and contracts between these services. SOA is the most basic solution to solve complex business modules, improve extensibility, maintainability and scalability. Our business services can distribute, combine, and use loosely coupled coarse-grained application components on demand over the network. The service layer is the foundation of SOA and can be invoked directly by the application, and different services are maintained by different teams.

  Effective Business Segmentation is the foundation of SOA

Two. SOA basic architecture diagram (take Spring-cloud as an example)

1. Registry: Typically, the interface is used as a contract to store service information exposed by the service provider, and the common Registry has zookeeper Eureka

2. Service Provider: Service Provider

3. Consumer: When a remote service interface needs to be invoked, the service provider must be found in the Registry Discovery service to make a remote method call

Three. Springcloud

Spring Cloud provides developers with the tools to quickly build common patterns in distributed systems (such as configuration management, service discovery, circuit breakers, intelligent routing, micro-proxies, control buses). with Spring cloud developers, you can quickly support services and applications that implement these patterns.

Gradle configuration:

Buildscript {ext {springbootversion= ' 1.5.8.RELEASE '} repositories {maven {URL"Http://maven.aliyun.com/nexus/content/groups/public/"}} dependencies {classpath ("Org.springframework.boot:spring-boot-gradle-plugin:${springbootversion}")}}allprojects {Apply plugin:' Java 'Apply plugin:' Idea 'Apply plugin:' Org.springframework.boot 'Sourcesets {main {java {srcdirs= ["Src/main/java"]} resources {Srcdirs= ["Src/main/resources"]}}} repositories {maven {URL"Http://maven.aliyun.com/nexus/content/groups/public/"}} ext {springcloudversion= ' DALSTON.SR3 '} dependencies {compile (' Org.springframework.cloud:spring-cloud-starter-config ') Compile (' Org.springframework.cloud:spring-cloud-config-server ') Compile' Org.springframework.cloud:spring-cloud-starter-eureka-server 'Compile' Org.springframework.boot:spring-boot-starter-actuator 'Compile' Org.springframework.cloud:spring-cloud-starter-ribbon 'Compile' Org.springframework.boot:spring-boot-starter-web 'Compile (' Org.springframework.boot:spring-boot-starter-cloud-connectors ') Testcompile (' Org.springframework.boot:spring-boot-starter-test ')} dependencymanagement {imports {Mavenbom"Org.springframework.cloud:spring-cloud-dependencies:${springcloudversion}"}}}group= ' Com.example 'version= ' 0.0.1-snapshot 'sourcecompatibility= 1.8targetcompatibility= 1.8
View Code

When Gradle downloads all the jar packages, create several project modules in turn:

Here's a description:

Register-center: Registration Center

Service-api: Interface Contract

Service-provider: Service Provider

Service-consumer: Service Consumer

Four. Implementation steps

4.1 Implementing the Registration Center:

APPLICATION.YML configuration:

  

Server:  Port:8000eureka:  client:    register-with-eureka:false    fetch-registry:false    Service-url:      defaultzone:http://localhost:8000/eureka/
View Code

Under the default settings, the Eureka Service registry will also attempt to register itself as a client, so we need to disable its client registration behavior.
  Register-with-eureka:false
Fetch-registry:false
Service-url: Address of registry access

Program Entry class:
 PackageCom.bdqn.springcloud.study.provider;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.cloud.netflix.eureka.server.enableeurekaserver;@ Enableeurekaserver@springbootapplication Public classRegistercenterprovider { Public Static voidMain (string[] args) {Springapplication.run (registercenterprovider.class, args); }}
View Code

@EnableEurekaServer activating Eureka Server-related configuration

4.2 Implementation Service-api

Defining an interface contract for exposing services

 Package Com.bdqn.springcloud.study.api; Import Com.bdqn.springcloud.study.dto.UserDTO; /**  @author*/Publicinterface  userservice {    userdto Finduser ();}
View Code

Defining DTOs

 Packagecom.bdqn.springcloud.study.dto; Public classUserdto {PrivateInteger ID; PrivateString name;  PublicInteger getId () {returnID; }     Public voidsetId (Integer id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }}
View Code

4.3 Implementing the service provider:

Gradle configuration: Rely on SERVICE-API first

dependencies{    Compile project (": Service-api")}
View Code

Configuration of the Application-yml:

Server:  port:8001spring:  application:    name: "Service-provider-demo" Eureka:  instance:    Prefer-ip-address:true  Client:    service-url:      defaultzone:http://localhost:8000/eureka/
View Code

Note: To configure the service address of the app name registry in this area

Interface Implementation class:

 PackageCom.bdqn.springcloud.study.provider.impl;ImportCom.bdqn.springcloud.study.api.UserService;ImportCom.bdqn.springcloud.study.dto.UserDTO;ImportOrg.springframework.stereotype.Service; @Service ("UserService") Public classUserserviceimplImplementsUserService {@Override Publicuserdto Finduser () {userdto userdto=Newuserdto (); Userdto.setname ("Zhang San Feng"); Userdto.setid (10); returnuserdto; }}
View Code

Controller:

 PackageCom.bdqn.springcloud.study.provider.controller;ImportCom.bdqn.springcloud.study.api.UserService;ImportCom.bdqn.springcloud.study.dto.UserDTO;Importorg.springframework.web.bind.annotation.GetMapping;ImportOrg.springframework.web.bind.annotation.RestController;ImportJavax.annotation.Resource; @RestController Public classUsercontroller {@ResourcePrivateUserService UserService; @GetMapping ("/USER")     Publicuserdto GetUser () {return  This. Userservice.finduser (); }}
View Code

Startup class:

 PackageCom.bdqn.springcloud.study.provider;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.cloud.client.discovery.enablediscoveryclient;@ Enablediscoveryclient@springbootapplication Public classserviceprovider { Public Static voidMain (string[] args) {Springapplication.run (serviceprovider.class, args); }}
View Code
@EnableDiscoveryClient: Annotations for enabling Discovery client implementations

Call to Browser access: http://localhost:8000

We see that the interface service has been successfully registered to the Eureka Center.


4.3 Implementing the service consumer:

Gradle configuration: Rely on SERVICE-API first
dependencies{    Compile Project (": Service-api")}
View Code

APPLICATION.YML configuration:

Server:  port:8002spring:  application:    name: "Service-consumer-demo" Eureka:  instance:    Prefer-ip-address:true  Client:    service-url:      defaultzone:http://localhost:8000/eureka/
View Code

To write a controller:

 PackageCom.bdqn.springcloud.study.consumer.controller;ImportCom.bdqn.springcloud.study.dto.UserDTO;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.cloud.client.loadbalancer.LoadBalancerClient;Importorg.springframework.http.ResponseEntity;Importorg.springframework.web.bind.annotation.GetMapping;ImportOrg.springframework.web.bind.annotation.RestController;Importorg.springframework.web.client.RestTemplate; @RestController Public classConsumercontroller {@AutowiredPrivateresttemplate resttemplate; @AutowiredPrivateloadbalancerclient loadbalancerclient; @GetMapping ("/getuser")     PublicString GetUser () {responseentity<UserDTO> responseentity = resttemplate.getforentity ("Http://SERVICE-PROVIDER-DEMO/user", Userdto.class); Userdto Userdto=Responseentity.getbody (); returnUserdto.getname (); }}
View Code

Note that we specify Service-provider's application name through http://service-provider-demo/user/to let the system discover the service from the registry.

To write a startup item:

 PackageCom.bdqn.springcloud.study.consumer;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.cloud.client.discovery.EnableDiscoveryClient;Importorg.springframework.cloud.client.loadbalancer.LoadBalanced;Importorg.springframework.cloud.netflix.eureka.EnableEurekaClient;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.web.client.RestTemplate, @SpringBootApplication @enablediscoveryclient Public classServiceconsumer {@Bean @LoadBalanced resttemplate resttemplate () {return Newresttemplate (); }     Public Static voidMain (string[] args) {Springapplication.run (serviceconsumer.class, args); }}
View Code

In the startup item, we configured a resttemplate idea @LoadBalanced annotation-modified resttemplate, with load-balancing capability of resttemplate, that is, each time a load balancing algorithm is used, from the list of available services, pick one to invoke.

At the end of the launch, we found one more service in the registry:

When we visit Http://localhost:8002/getUser we get the following indication that our service is running successfully:

When we stop register-center, we find that the access address can still get the result, indicating that the consumer is locally cached.

The SOA Foundation for Springcloud Learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.