本博客的参考文章:https://www.fangzhipeng.com/springcloud/2017/06/01/sc01-eureka.html
一、server端的配置
右键工程->创建model-> 选择spring initialir 如下图:
点击next,配置好文件名等基本内容,继续下一步,选择Spring cloud Discovery-->server
这样就创建完成一个server,client同理
在springboot工程的启动application类上加@EnableEurekaServer,该注解是指启动一个服务注册中心
package com.xtc.springcloudserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class SpringCloudServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudServerApplication.class, args);
}
}
配置application.properties配置文件,用yml格式的也可以,选择自己喜欢的方式。
server.port=8761
eureka.instance.hostname=localhost
//eureka.client.registerWithEureka:false和fetchRegistry:false来表明自己是一个eureka server.
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
最后看一下效果:访问:http://localhost:8761/
二、创建一个服务提供者 (eureka client)
创建模块的方式同上,要加上一个web的选项方便测试,否则就需要自己添加web的依赖
启动类代码
package com.xtc.springcloudclient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
@EnableEurekaClient//表明自己是EurekaClient
public class SpringCloudClientApplication {
@Value("${server.port}")
private String port;
public static void main(String[] args) {
SpringApplication.run(SpringCloudClientApplication.class, args);
}
@GetMapping("/hi")
public String f(@RequestParam String name){
return "hi "+name+",i am from port:" +port;
}
}
配置文件的内容
#注明自己的服务注册中心的地址
eureka.client.service-url.defaultZone= http://localhost:8761/eureka/
#自身端口号
server.port=8762
#以后的服务与服务之间相互调用一般都是根据这个name
spring.application.name=service-first
启动项目测试一下,记住先启动server,在启动client,不然会报错:
访问:http://localhost:8762/hi?name=heihiehie
hi heihiehie,i am from port:8762
结束