Ribbon快速开始

1、引入必要的maven依赖:


    org.springframework.boot
    spring-boot-starter-parent
    1.5.9.RELEASE
    


    
        
            org.springframework.cloud
            spring-cloud-dependencies
            Edgware.RELEASE
            pom
            import
        
    


    
        org.springframework.cloud
        spring-cloud-starter-eureka
    
    
        org.springframework.cloud
        spring-cloud-starter-ribbon
    

2、创建springboot的启动类:

@SpringBootApplication
@EnableDiscoveryClient
public class HelloApplicaton {

    //这里就是创建一个负载均衡的RestTemplate Bean
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }


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

3、resource下配置启动文件:application.yml或者application.properties

server:
  port: 9091
spring:
  application:
    name: post-service
eureka:
  instance:
    hostname: localhost
  client:
    serviceUrl:
        defaultZone: http://localhost:1111/eureka/

4、创建消费者请求接口:

@RestController
public class HelloController {

   //注入前面创建的负载均衡的RestTemplate
    @Autowired
    public RestTemplate restTemplate;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String postHello(){
     //使用有负载均衡能力的RestTemplate请求微服务
     return   restTemplate.getForEntity("http://HELLO-SERVICE/hello"
                ,String.class,"").getBody();
    }
}

注:这里的HELLO-SERVICE就是注册中心存在的微服务的名称,这个大家应该都很清楚;

这样一个具有负载均衡能力的消费者接口就创建成功了!

你可能感兴趣的:(Ribbon快速开始)