【Spring Cloud】三、Eureka Consumer 服务注册中心消费者调用服务

消费者和服务提供者使用同样的eureka服务端注册中心地址,调用注册中心的服务

maven结构如下:


application相关配置如下:

spring.application.name=consumer-demo
eureka.client.service-url.defaultZone=http://localhost:8060/eureka

server.port=8080

代码如下:

package com.chiwei.eureka;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @Type Bootstrap.java
 * @Desc 
 * @author chiwei
 * @date 2017年11月9日 下午5:24:53
 * @version 
 */
/**
 * @author chiwei
 *
 */
@EnableDiscoveryClient
@SpringBootApplication
public class Consumer {

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

    /**
     * 主函数入口
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Consumer.class);
        // 不启动web服务
        // app.setWebEnvironment(false);
        app.run(args);
    }

}

@RestController
class HelloController {
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {
        return restTemplate.getForEntity("http://service-demo/hello", String.class).getBody();
    }
}

/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2017年11月9日 chiwei create
 */

启动消费者,浏览器调用服务如下:


调用服务如下:







猜你喜欢

转载自blog.csdn.net/chiweitree/article/details/78626261