Spring Cloud 服务消费者

2023-01-01  本文已影响0人  Tinyspot

1. 微服务调用

1.2 服务消费者

在微服务架构中,业务会被拆分成一个独立的服务,服务与服务的通讯基于 http restful. Spring Cloud 有两种服务调用方式,一种是 Ribbon + RestTemplate, 另一种是 Feign

2. Ribbon

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>com.netflix.ribbon</groupId>
        <artifactId>ribbon-loadbalancer</artifactId>
        <version>2.3.0</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

application.yml 配置

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

spring:
  application:
    name: concrete-ribbon

server:
  port: 9010

2.2 Ribbon 客户端

@SpringBootApplication
@EnableDiscoveryClient
public class ConcreteRibbonApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConcreteRibbonApplication.class, args);
    }
}
@RestController
public class AdminController {

    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("/invoke")
    public String invoke(String message) {
        // 去调用 Eureka 的服务提供者 concrete-eureka-client
        return restTemplate.getForObject("http://concrete-eureka-client/show?message=" + message, String.class);
    }
}

注入 RestTemplate, 并添加注解 @LoadBalanced, 声明该 RestTemplate 用于负载均衡

@Configuration
public class RestTemplateConfiguration {

    @Bean
    @LoadBalanced // 默认负载均衡算法:轮询
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

请求地址 http://localhost:9010/invoke?message=Hello

3. Feign

3.1 配置

<dependencies>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
  </dependency>
</dependencies>
server:
  port: 8020

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

spring:
  application:
    name: concrete-feign

3.2 启动类

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class ConcreteFeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConcreteFeignApplication.class, args);
    }
}

3.3 示例

@RestController
public class AdminController {

    @Resource
    private AdminService adminService;

    @RequestMapping("/invoke")
    public String invoke(String message) {
        return adminService.invoke(message);
    }
}
@FeignClient("concrete-eureka-client")
public interface AdminService {
    @RequestMapping("/show")
    String invoke(@RequestParam(value = "message") String message);
}

@FeignClient 远程服务名
@RequestMapping 远程服务方法名
@RequestParam 参数名

访问 http://localhost:8020/invoke?message=hello

上一篇 下一篇

猜你喜欢

热点阅读