在学习spring cloud 微服务时发现消费者无法注册到注册中心

已注册两个服务:

下面发一下服务消费者的代码: 

application 主入口:

@EnableDiscoveryClient   //开启发现服务功能
@SpringBootApplication
public class ConsumerUserApplication {

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

    @LoadBalanced  //使用负载均衡机制
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

Controller:

@RestController
public class UserController {

    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/buy")
    public String buyTicket(String name){
        String s = restTemplate.getForObject("http://PROVIDER-TICKET/ticket", String.class);
        return name+"购买了:"+s;
    }
}

application.yml:

spring:
  application:
    name: consumer-user
server:
  port: 8200


eureka:
  instance:
    prefer-ip-address: true #注册服务的时候使用服务的IP地址
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

启动主程序以后发现服务并没有注册到注册中心中

后来好奇访问了一下页面,结果页面报了500:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Mar 11 14:39:27 CST 2019
There was an unexpected error (type=Internal Server Error, status=500).
I/O error on GET request for "http://PROVIDER-TICKET/ticket": PROVIDER-TICKET; nested exception is java.net.UnknownHostException: PROVIDER-TICKET

参考了一下百度上的问题,大概意思是导入的包不对的缘故

导入下列包:

       <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>


    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

问题解决,成功注册到注册中心 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐