建立基於Spring Clould的服務提供者_spring-cloud

來源:互聯網
上載者:User
簡單幾步,建立spring-boot微服務提供者。假設要建立一個user服務:
1、引入依賴(pom.xml):
<dependencies><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.SR3</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>

2、設定檔(application.yml)中指定註冊中心: 假設有三個註冊中心組成高可用的叢集:
eureka:  client:    serviceUrl:      defaultZone: http://192.168.0.9:58000/eureka/,http://192.168.0.10:58000/eureka/,http://192.168.0.18:58000/eureka/  instance:    preferIpAddress: true

3、項目配置啟用Controller中對服務資訊的輸出(通過@EnableDiscoveryClient註解 ):
@EnableDiscoveryClient@SpringBootApplicationpublic class UserApplication {public static void main(String[] args) {SpringApplication.run(UserApplication.class, args);}}

4、通過建立Controller提供服務:
@RestControllerpublic class UserController {protected final Logger logger = LoggerFactory.getLogger(getClass());@AutowiredUserService userService;/** * 根據使用者id擷取電話號碼 * @param userId * @return 電話號碼 */@RequestMapping(value = "/getPhoneNoByUserId", method = RequestMethod.GET)public String getPhoneNoByUserId(@RequestParam Integer userId) {logger.debug("getPhoneNoByUserId received. userId={}", userId);return userService.getPhoneNoByUserId(userId);}}

//Service和其他代碼略。。。
5、啟動,檢查註冊中心中是否可以看到user服務: 訪問三個註冊中心的任意一個: http://192.168.0.9:58000/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.