Declarative service call Spring Cloud Feign (c) the use of notes

Build a service environment

Add module in spring-cloud-demo project: demo-feign-consumer
join rely on pom.xml file:

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-feign</artifactId>
    </dependency>
</dependencies>

Increase application.properties file in the resource directory, add the following:

################## 服务配置 ###############
server.port=9257
spring.application.name=demo-feign-consumer
#注册到注册中心
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/,http://localhost:8762/eureka/

Creating a startup class: FeignConsumerApplication.java, add the following:

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class FeignConsumerApplication {

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

Add Service category: DemoFeignService.java, add the following:

@FeignClient(value = "demo-service")
public interface DemoFeignService {

    @RequestMapping(value = "/port", method = RequestMethod.GET)
    String hello();
}

Add Controller class: DemoFeignController.java, add the following:

@RestController
public class DemoFeignController {
    @Autowired
    DemoFeignService demoFeignService;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String port() {
        return demoFeignService.hello();
    }
}

Were used demo-service project to build the port before running 9806,9807
run demo-feign-consumer items, visit http: // localhost: 9257 / hello , show the following:
the I AM demo-service, the I'm from Port: 9808
so to achieve a declarative service calls, numerous visits to different ports in order, return, indicating that load balancing has been achieved, the default is to use polling policy

Load Balancing Configuration

Start adding the class file FeignConsumerApplication.java methods:
// new random policy
@Bean
public IRule ribbonRule () {
return new new RandomRule (); // here to choose a random policy, corresponding to the configuration file
}

9806,9807 ports were used to build the demo-service project before you run
and then run the demo-feign-consumer items, visit: http: // localhost: 9257 / hello, you will find several multi-access port is the return of a random
I Demo-Service-AM, from the I'm Port: 9806
the I AM-Demo-Service, the I'm from Port: 9806
the I AM-Demo-Service, the I'm from Port: 9806
the I AM-Demo-Service, the I'm from Port: 9807

Guess you like

Origin www.cnblogs.com/yhongyin/p/11183853.html