Three ways for sprigclound to call other microservices

Three ways to call other microservices

1. Rest method (underlying Httpclient tool)

@SuppressWarnings("unchecked")

@Service

public class MemberService {

    @Autowired

    RestTemplate restTemplate;

        public List<String> getOrderByUserList() {

            return restTemplate.getForObject("http://service-member/getUserList",

                     List.class);//Return value.class

        }

}



2. Ribbon method (underlying Httpclient tool)

In the startup class of the project, register with the service center through @EnableDiscoveryClient; and inject a bean: restTemplate into the ioc of the program; and use the @LoadBalanced annotation to indicate that this restRemplate enables load balancing. Use load balancing strategy to rotate to call service interface

@EnableEurekaClient
@SpringBootApplication
public class AppOrder {

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

	@Bean
	@LoadBalanced
	RestTemplate restTemplate() {
		return new RestTemplate();
	}

}

2. Feign method (underlying Httpclient tool) feignClient has used the ribbon's own load balancing by default

Startup class @Enable FeignClients

fegin code   

@FeignClient(value="service-member",fallback=MemberFeignService.class)
public interface MemberFeign {
	@RequestMapping("/getMemberAll")
	public List<String> getOrderByUserList(); //Write the method name as you like
}

     * 1、这里需要设置请求的方式为 RequestMapping 注解,用 GetMapping 注解是运行不成功的,即 GetMapping 不支持。
     *
     * 2、注解 PathVariable 里面需要填充变量的名字,不然也是运行不成功的。
        如果入参是一个对象的话,那么这个方法在 feign 里面默认为 POST 方法,就算你写成 GET 方式也无济于事。
 首先通过@EnableFeignCleints注解开启FeignCleint
 根据Feign的规则实现接口,并加@FeignCleint注解
 程序启动后,会进行包扫描,扫描所有的@ FeignCleint的注解的类,并将这些信息注入到ioc容器中。
 当接口的方法被调用,通过jdk的代理,来生成具体的RequesTemplate
 RequesTemplate在生成Request
 Request交给Client去处理,其中Client可以是HttpUrlConnection、HttpClient也可以是Okhttp
 最后Client被封装到LoadBalanceClient类,这个类结合类Ribbon做到了负载均衡。




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325899822&siteId=291194637