1. 程式人生 > >spring cloud(一、新建微服務)

spring cloud(一、新建微服務)

一、新建spring Cloud專案

選擇cloud discovery->eureka server建立新專案

二、新建一個服務註冊中心(eureka-client)

在啟動類上加上@EnableEurekaServer

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

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

application.yml配置:

server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

spring:
  application:
#    專案名
    name: eureka-client

啟動專案:http://localhost:8761

三、建立一個服務提供者(eureka-server)

新建一個springcloud專案

在啟動類上加上@EnableEurekaClient註解

@EnableEurekaClient
@RestController
@SpringBootApplication
public class EurekaClientApplication {

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

	@Value("${server.port}")
	String port;

	@RequestMapping("/hi")
	public String home(@RequestParam(value = "name", defaultValue = "forezp") String name) {
		return "hi " + name + " ,i am from port:" + port;
	}
}

配置application.yml

server:
  port: 8762

spring:
  application:
    name: eureka-server

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

開啟http://localhost:8761可以看到服務已啟動

  呼叫介面http://localhost:8762/hi

git原始碼:https://github.com/lrn-white/springcloud