springcolud-服务消费者

1.pom文件添加服务消费者的起步依赖


   
      org.springframework.boot
      spring-boot-starter-web
   
   
      org.springframework.cloud
      spring-cloud-starter-netflix-eureka-client
   
   
      org.springframework.cloud
      spring-cloud-starter-netflix-ribbon
   


2.配置eureka消费地址

server.port=8088
 
spring.application.name=cons
 
spring.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka_server/


3.启动类注解@EnableEurekaClient,并将restTemplate注入到ioc容器,并使用@LoadBalanced注解声明开启负载均衡

package com.kejin.cons;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
public class EurekaConsApplication {

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

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

}


4.测试,编写一个controller,注入RestTemplate用其调用服务提供者接口 

package com.kejin.cons.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class RibbonController {

    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/getPortInfo")
    public String getPoducerInfo() {
    	String result = this.restTemplate.getForObject("http://service-eureka-clienteureka/getPortInfo", String.class);
        return result;
    }
}

 

你可能感兴趣的:(springcolud-服务消费者)