springcloud微服务实战 学习笔记三 服务消费者

2017-08-04  本文已影响53人  maylor_zhu

第一种方式LoadBalancerClient

第二种方式Ribbon

配置文件修改端口号即可
修改Application.java,在RestTemplate上添加注解

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

controller修改为

    @GetMapping("/hello2")
    public String hello2(){
        return restTemplate.getForObject("http://eureka-client/hello",String.class);
    }

第三种方式Feign

配置文件修改端口号即可

Application.java添加注解@EnableFeignClients支持Feign客户端

    @EnableFeignClients
    @EnableDiscoveryClient
    @SpringBootApplication
    public class Application {
    
        public static void main(String[] args) {
            new SpringApplicationBuilder(Application.class).web(true).run(args);
        }
    }

创建一个接口
@FeignClient("eureka-client")设置使用的服务名称

    @FeignClient("eureka-client")
    public interface DemoService {
    
        @GetMapping("/hello")
        String hello();
    }

controller

    @RestController
    public class DemoController {
    
        Logger logger = LoggerFactory.getLogger(this.getClass());
        @Autowired
        DemoService demoService;
        @GetMapping("/hello")
        public String hello(){
    
            return demoService.hello();
        }
    }

三种方式可以混合使用,第二种方式因为将RestTemplate对象添加了注解,所以第一种方式就不能直接使用了,只能利用其它方式发送http请求获取数据。

上一篇下一篇

猜你喜欢

热点阅读