3、創(chuàng)建SpringCloud server消費(fèi)者(ribbon)

先創(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)用接口。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容