第一步:引入依赖 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud_myproject</artifactId>
<groupId>com.idea</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud_provider</artifactId>
<packaging>war</packaging>
<name>springcloud_provider Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--eureka server-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<!-- spring boot test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<finalName>springcloud_provider</finalName>
</build>
</project>
第二步:创建入口类
@EnableDiscoveryClient与@EnableEurekaClient完成功能一直都是代表注册中心的客户端
唯一区别:@EnableEurekaClient只能用于eurekaServer的注册中心,@EnableDiscoveryClient能用于任何的注册中心(推荐使用)
@SpringBootApplication
@EnableDiscoveryClient
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class,args);
}
}
第三步:application.yml
server:
port: 8088
spring:
application:
name: hello-client
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/ #将服务注册到注册中心
第四步:创建controlle类进行服务的调用
@RestController
@RequestMapping("/user")
public class HelloController {
@Value("${server.port}")//通过配置文件配置的全局变量 用@Value注解
private String port;
@RequestMapping("/hello")
public String helloController(@RequestParam String name){
return "hello:"+name+"=====你好:"+port;
}
}
启动注册中心,可以看到服务已经注册到注册中心了
访问controller可以看到如下内容: