Introduction to spring cloud
eureka
As a registry, eureka plays an important role in microservices. At present, eureka and zookeeper are the mainstream registries. eureka is AP, zookeeper is CP. (CAP theory)
Architecture diagram
As can be seen from the architecture diagram, eureka adopts cs architecture. Service provider and consumer as client. The provider registers its services with eureka. After the consumer goes to eureka to get the provider information, the call is implemented in RPC mode. eureka stores metadata information,
case
- Project initialization pom file
Parent module introduction springcloud assembly <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <!--All jar Pack into one pom Papers. avoid pom File is too large.--> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
- Introduce dependency [before you start again, you need to ensure that your project supports spring cloud components]
eureka client
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
eureka server
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency>
eurekaserver applicayion.yml
server: port: 8761 //Port number spring: application: name: eureka // eureka name eureka: instance: hostname: eureka client: fetch-registry: false //You don't need to get information from the server because it's a single node, register-with-eureka: false //Close self registration, service-url: defaultZone: http://${Eureka. Instance. Hostname}: ${server. Port} / Eureka / / / Eureka registered address,
eurekaclient application.yml
server: port: 9001 spring: application: name: eurek-client-ad-sponsor eureka: client: service-url: defaultZone: http://localhost:8761/eureka note that the address here is the local 8761 address. If you configure to write ip or domain name on another machine instance: //These configurations can be unconfigured. They are mandatory, instance-id: power-1 #This instance is registered to the unique instance ID of the eureka server prefer-ip-address: true #Show IP address or not leaseRenewalIntervalInSeconds: 10 #How long does it take for the eureka client to send a heartbeat to the eureka server, indicating that it is still alive, with a default of 30 seconds (in seconds as configured below) leaseExpirationDurationInSeconds: 30 #After receiving the last heartbeat from the instance, how long does the Eureka server need to wait before deleting the instance? The default is 90 seconds
eurekaserverpplication
@SpringBootApplication @EnableEurekaServer The server sets this annotation public class eurekaApplication { public static void main(String[] args) { SpringApplication.run(eurekaaserverpplication.class,args); } }
eureka cluster
In order to meet the high availability of production environment, erueka must be A cluster mode. After the service is registered with eureka, the information between eureka servers is synchronized. For configuration information, all client addresses need to be written in the client. For the server, three machines are assumed to be ABC. Then A register address write BC and so on. Just configure and build Baidu. There are many demo s
Zuul
In the microservice architecture, the original call of a request on a machine becomes a cross network RPC call. The advantage of this is that service splitting is easy to manage, but it also brings the disadvantage that calls between services may become particularly responsible due to complex business calls. The client request address has also become particularly complex. So we need a unified entrance. zuul implements this function in microservices. zuul has two functions, one is routing and the other is filtering. zuul is also a service registered in eureka
Route
In development, the path is to map the request to the corresponding processing method,
zuul: prefix: /immoc All requests are preceded by a prefix, which is removed by default routes: sponsor: Custom name path: /ad-sponsor/** Match all paths. /*Match only one level path serviceId: eurek-client-ad-sponsor Request mapped to client id strip-prefix: false search: path: /ad-search/** serviceId: eurek-client-ad-search strip-profix: false // Remove prefix or not. false means do not remove prefix # 127.0.0.1:9000/imooc/ad-search/fetchAds
filter
Filter is the core component of zuul, which defines four standard filter types. These filters have corresponding ranges.
PRE: call before request is routed.
ROUTING: filtering requests to microservices
POST: executed after routing to the microservice.
ERROR: when an ERROR occurs
Simple demo
@Slf4j @Component public class PreRequestFilter extends ZuulFilter { @Override public String filterType() { return FilterConstants.PRE_TYPE; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); ctx.set("startTime",System.currentTimeMillis()); return null; } }
Feign
A declarative web service client is actually to help us implement rpc calls. After getting the registration information from Eureka, the service uses feign to realize remote call. It is used to define an interface, and then add annotations on it. At the same time, it also supports JAX-RS standard annotations. Feign also supports pluggable encoders and decoders. Spring Cloud encapsulates feign to support Spring MVC standard annotations and HttpMessageConverters. Feign can be combined with Eureka and Ribbon to support load balancing.
demo
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency
Annotate the startup class: @ EnableFeignClients
@FeignClient(value = "eurek-client-ad-sponsor",fallback = SponsorClientHystrix.class) public interface SponsorClient { @RequestMapping(value = "/ad-sponsor/get/adPlan",method = RequestMethod.POST) CommonResponse<List<AdPlan>> getAdPlans(@RequestBody AdPlanGetRequest request); }
Then inject the interface where necessary.
To learn the spring cloud framework, you must write Eureka feign zuul ribbon htstrix