SpringCloud microservice entry case

First of all, we have to understand what its function is, in order to complete the mutual calling of interfaces between different microservices
Please add a picture description

service call

1. Run the Nacos registration center

1. Nacos download and installation
Download address: https://github.com/alibaba/nacos/releases
2. Windows startup Nacos
reference: https://github.com/alibaba/nacos
Decompression: Decompress the downloaded compressed package and
start: startup.cmd -m standalone
3. Visit
http://localhost:8848/nacos

Username and password: nacos/nacos

2. Service Discovery

First, we create a springBoot project
1. Introduce dependencies and
configure Nacos client dependencies in the service-base module

<!--服务发现-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

2. Add service configuration information
Put the microservices that need to be registered to the registration center into the configuration file and add the configuration (in human terms, add it to the configuration file of each microservice to register it with the nacos service) #spring
:
cloud :
nacos:
discovery:
server-addr: localhost:8848 # nacos service address
3. Start microservices
Start the registered microservices, check "service management => service list", you can see the registered microservices
insert image description here

3. The introduction of OpenFeign to the consumer side

Configure OpenFeign dependencies in the service-base module (actually OpenFeign dependencies are required on the service consumer side)

<!--服务调用-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2. Add annotations to the startup class
Add the following annotations to the startup class of service-sms, indicating that I can be called remotely

@EnableFeignClients

Fourth, the remote call of the interface

Add remote call to service-sms
// @FeignClient(value = "service-core") indicates which service I call value is the name of the service
1, CoreUserInfoClient

@FeignClient(value = "service-core")
public interface CoreUserInfoClient {
    
    

    @GetMapping("/api/core/userInfo/checkMobile/{mobile}")
    boolean checkMobile(@PathVariable String mobile);
}

Five, timeout control

The default connection timeout of openfeign is 1 second, and a remote call timeout error is likely to occur during the test.
The following configuration can be added to the configuration file:
feign:
client:
config:
default:
connectTimeout: 10000 #Connection timeout configuration
readTimeout: 600000 #Execute timeout configuration

6. There may be a remote call service, which is blown (the server suddenly hangs up, and I still want to call this interface)

We adopt the process of fusing and downgrading. If there is a remote call service, it is fusing. We create an implementation class in this service that does not handle the interface, and return data to the user to prompt. Guaranteed, in the case that the remote interface cannot be accessed I can also access the local interface under

The first step is to introduce dependencies in services that require remote calls

<!--服务容错-->
<dependency>
    <groupId>com.alibaba.cloud</groupId> 
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

2. Enable Sentinel support
Enable Feign's support for Sentinel in the yml configuration file of service-sms

#开启FeignSentinel的支持
#feign:
  sentinel:
    enabled: true

3. Create a fault-tolerant class// If the remote call interface fails, I will call the local interface and give the user data

@Service
@Slf4j
public class CoreUserInfoClientFallback implements CoreUserInfoClient {
    
    
    @Override
    public boolean checkMobile(String mobile) {
    
    
        log.error("远程调用失败,服务熔断");
        return false;
    }
}

4. Specify the fuse class
Add the fallback attribute value for the OpenFeign remote call interface without specifying the fault tolerance class

@FeignClient(value = "service-core", fallback = CoreUserInfoClientFallback.class)
public interface CoreUserInfoClient {
    
    

service gateway

First of all, let's talk about its function: I can access the URL of the same port and access the interface of different servers

Please add a picture description

1. Create the module service-gateway

Create a common maven module
Artifact: service-gateway
2. Configure pom
Add the following dependencies to the pom of api-gateway

<dependencies>
    <!-- 网关 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <!--服务注册-->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
</dependencies>

3. Configure application.yml

server:
  port: 80 # 服务端口

spring:
  profiles:
    active: dev # 环境设置
  application:
    name: service-gateway # 服务名
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 # nacos服务地址
    gateway:
      discovery:
        locator:
          enabled: true # gateway可以发现nacos中的微服务,并自动生成转发路由

4. Create a startup class

@EnableDiscoveryClient indicates that it is a gateway microservice

@SpringBootApplication
@EnableDiscoveryClient
public class ServiceGatewayApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(ServiceGatewayApplication.class, args);
    }
}

5. Test automatic routing and forwarding

Http://localhost/service-core/admin/core/integralGrade/list
rule:
http://Gateway_HOST:Gateway_PORT/serviceId/**
When we don't want to call again, we use the above default method to access the gateway. We can do it below Configure routing yourself

2. Routing configuration

1.
Add routing configuration to the basic configuration application.yml file

#spring:
# cloud:
#   gateway:
      routes:
      - id: service-core
        uri: lb://service-core
        predicates:
        - Path=/*/core/**
      - id: service-sms
        uri: lb://service-sms
        predicates:
        - Path=/*/sms/**
      - id: service-oss
        uri: lb://service-oss
        predicates:
        - Path=/*/oss/**

2. Test route forwarding
http://localhost/admin/core/integralGrade/list

Gateway configuration will have a cross-domain problem and @CrossOrigin is in conflict, so it cannot solve the cross-domain problem
Let's solve this problem

3. Cross-domain configuration

Add cross-domain configuration in api-gateway

@Configuration
public class CorsConfig {
    
    
    @Bean
    public CorsWebFilter corsFilter() {
    
    
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true); //是否允许携带cookie
        config.addAllowedOrigin("*"); //可接受的域,是一个具体域名或者*(代表任意域名)
        config.addAllowedHeader("*"); //允许携带的头
        config.addAllowedMethod("*"); //允许访问的方式

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}

2. Delete the back-end cross-domain configuration
Delete the cross-domain annotation @CrossOrigin in the microservice

Guess you like

Origin blog.csdn.net/qq_50319351/article/details/128595427