本文创建方式采用intellij IDEA 创建项目
1.创建基于Eureka的注册中心。
在打开项目中右键,选择new 选择moudle
然后下一步
输入要创建的项目的信息
选择web下面的web,选择cloud discovery下面的 Eureka server 下一步,创建项目
然后同步pom.xml文件内容、
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.3.RELEASE
com.example
server
0.0.1-SNAPSHOT
server
Demo project for Spring Boot
1.8
Greenwich.SR1
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
spring-milestones
Spring Milestones
https://repo.spring.io/milestone
在启动文件中选择
@SpringBootApplication
@EnableEurekaServerpublic classServerApplication {public static voidmain(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}
配置文件
server:
port: 8000
eureka:
instance:
hostname: localhost
client:
fetch-registry: false
register-with-eureka: false
serviceUrl:
defaultZone: http://localhost:8000/eureka/
spring:
application:
name: spring-cloud-eureka
创建完,我们去运行下,运行正常后,我们去访问localhost:8000, 到下面的界面,这样我们Eureka 注册中心就创建成功,
下面我们去创建server端,和client;
server端呢创建中与Eureka选择不同的在于cloud discovery中,这里需要选择cloud Discovery
然后创建完,去同步对应的pom.xml文件
在启动类编写如下
@SpringBootApplication
@EnableDiscoveryClientpublic classServeroneApplication {public static voidmain(String[] args) {
SpringApplication.run(ServeroneApplication.class, args);
}
}
配置文件
server:
port:8001eureka:
instance:
hostname: localhost
client:
serviceUrl:
defaultZone: http://localhost:8000/eureka/
spring:
application:
name: spring-serverserver
我们需要编写一个提供服务的接口
@RestControllerpublic classHelloController {
@RequestMapping("/hello")publicString indesx(@RequestParam String name) {return "hello "+name+",this is first messge";
}
}
这样我们就可以实现我们的server端
然后我们去创建client端
client端多需要在server上创建多一个Feign
那么我们在启动类,如下
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClientspublic classDemoApplication {public static voidmain(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
配置文件
server:
port:8002eureka:
instance:
hostname: localhost
client:
serviceUrl:
defaultZone: http://localhost:8000/eureka/
spring:
application:
name: spring-client
那么我们去写调用server的服务
@FeignClient(name= "spring-serverserver")public interfaceHelloRemote {
@RequestMapping(value= "/hello")public String hello(@RequestParam(value = "name") String name);
}
实现接口
@RestControllerpublic classConsumerController {
@Autowired
HelloRemote lloRemote;
@RequestMapping("/hello/{name}")public String index(@PathVariable("name") String name) {returnlloRemote.hello(name);
}
}
这样我们就实现了服务的注册与调用。
那么我们去启动服务进行测试,服务注册成功,我们去启动服务调用端
服务调用端成功,
那么我们去测试下,我们先去测试看单独访问服务是否正常
输入http://localhost:8001/hello?name=liwanlei
显示
那么我们看下另外一个调用这个服务的服务
http://localhost:8002/hello/name
那么我们看下返回
这样我们调试成功。
户端已经成功的通过feign调用了远程服务,并且将结果返回到了浏览器。