先創(chuàng)建一個(gè)普通的SpringBoot項(xiàng)目,然后添加SpringCloud服務(wù)消費(fèi)者所需的配置即可。
pom.xml 添加內(nèi)容
<!--使用SpringBoot1.5.3版本-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR7</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
application.yml文件配置
eureka:
client:
serviceUrl:
#指定服務(wù)端地址
defaultZone: http://localhost:8000/eureka/
在啟動(dòng)類中調(diào)用在server中已經(jīng)注冊的服務(wù)
@EnableDiscoveryClient
@SpringBootApplication
public class SpringclientApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
new SpringApplicationBuilder(SpringclientApplication.class).web(true).run(args);
}
創(chuàng)建Controller調(diào)用服務(wù)接口
@RestController
public class MainController {
@Autowired
RestTemplate restTemp;
@RequestMapping("/user/{name}")
public String get(@PathVariable("name") String name){
return restTemp.getForEntity("http://db-service:8085/user/" + name, String.class).getBody();
}
}
運(yùn)行該項(xiàng)目,在瀏覽器中輸入 http://localhost:8086/user/bin 連接,即可調(diào)用接口。