springboot 之集成springcloud eureka

前言

一直沒機會做spring生態(tài)圈的框架,公司選擇的是一些小眾的微服務(wù),鑒于此考慮,豐富自己的技術(shù)棧,花了兩天時間從網(wǎng)上各網(wǎng)站上學習了springboot一些基礎(chǔ)知識。
本章只介紹springboot微服務(wù)集成springcloud,以及其eureka組件,將前一章的springboot微服務(wù)框架作為springcloud分布式架構(gòu)中的子微服務(wù),用springcloud管理。

環(huán)境準備

  • IntelliJ IDEA
  • 前一章中搭建的微服務(wù)框架
  • 前一章之后,對目錄結(jié)構(gòu)進行了整改


    工程目錄下新建demo目錄.png

    將以下目錄結(jié)構(gòu)移動到demo目錄下:


    目錄移動.png

    移動后如下.png

    移動完之后,刪掉idea的配置文件:.idea、***.iml,然后關(guān)掉idea,重新打開,open選擇此工程,重新生成配置文件。

    open之后,配置SDK,然后你會發(fā)現(xiàn)demo下的pom并沒有被idea的maven管理起來,你需要將其添加到此project的modules中,操作如下:


    導入modules.png

    選擇需要導入的包.png

    選擇import-maven-finish.png

    導入完成后如下結(jié)構(gòu):
    導入結(jié)果.png

    以上操作一般用于用idea對目錄結(jié)構(gòu)進行整改,請酌情使用。

開始集成springcloud

通過idea搭建eureka server

  1. 在工程名上右鍵新建modules:


    新建modules.png

    選擇spring Initializr.png

    輸入artifact.png

    勾選Eureka Server.png

    finish.png

    完成后idea會自動幫你把module導入到此工程中,并將對應功能的包標識為相應的顏色


    pom.xml.png

    可以看到pom.xml中生成的spring-cloud.version是Hoxton.SR1,此版本適配于springboot 2.2.x版本,稍后再demo中集成eureka client時,也使用這個版本。
  2. 將默認生成的application.properties修改為application.yml,并配置內(nèi)容:


    application.yml.png

server:
  port: 8082

#eueka 主機名
eureka:
  instance:
    hostname: eureka-service
  client:
    #不注冊自己
    register-with-eureka: false
    #獲取服務(wù)
    fetch-registry: false
    #提供者和消費者的注冊地址
    service-url:
      defaultZone: http://localhost:8082/eureka/
  1. 最后在EurekaApplication前加上注解@EnableEurekaServer,就可以啟動了,idea會自動將EurekaApplication添加到springboot啟動services管理中,如果未檢測,可以手動添加,右鍵EurekaApplication,選擇Create 'EurekaApplication'...,就可以將其加入到Services中。


    運行結(jié)果.png

    eureka管理界面.png

在demo微服務(wù)中集成eureka client

  1. demo下pom中添加依賴


    依賴配置.png

    依賴配置.png
        <spring-cloud.version>Hoxton.SR1</spring-cloud.version>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
  1. 配置demo的application.yml


    圖片.png
  application:
    name: provider
eureka:
  instance:
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://localhost:8082/eureka/
  1. 在DemoApplication前配置@EnableDiscoveryClient注解,標識當前應用是可被Eureka Server發(fā)現(xiàn)的,并在其中增加Bean,對restTemplate注解成啟用負載均衡


    DemoApplication
package com.example.demo;

import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
@MapperScan("com.example.demo.mapper")
@EnableScheduling
@EnableTransactionManagement
@Slf4j
@EnableDiscoveryClient
public class DemoApplication {

    public static void main(String[] args) {
        log.info("DemoApplication run enter...");
        SpringApplication.run(DemoApplication.class, args);
    }

    //啟用負載均衡,默認算法是輪詢
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
  1. 在controller下定義兩個接口,用于接口間通過注冊發(fā)現(xiàn)調(diào)用接口,此示例中使用demo微服務(wù)提供的兩個接口,模擬成兩個微服務(wù),接口調(diào)用通過Eureka提供的接口互相訪問。


    producer.png

    consumer.png
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 類功能描述:<br>
 * <ul>
 * <li>類功能描述1<br>
 * <li>類功能描述2<br>
 * <li>類功能描述3<br>
 * </ul>
 * 修改記錄:<br>
 * <ul>
 * <li>修改記錄描述1<br>
 * <li>修改記錄描述2<br>
 * <li>修改記錄描述3<br>
 * </ul>
 *
 * @author xuefl
 * @version 5.0 since 2020-01-15
 */
@RequestMapping("/producer")
@RestController
public class ProducerController {

    @Autowired
    private UserService userService;

    @GetMapping("/get_user")
    @ApiOperation(value="get_user",httpMethod = "GET",notes="test get_user",produces = MediaType.APPLICATION_JSON_VALUE)
    public List<User> getAllUser(){
        return userService.selectAll();
    }
}
package com.example.demo.controller;

import com.example.demo.entity.User;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 類功能描述:<br>
 * <ul>
 * <li>類功能描述1<br>
 * <li>類功能描述2<br>
 * <li>類功能描述3<br>
 * </ul>
 * 修改記錄:<br>
 * <ul>
 * <li>修改記錄描述1<br>
 * <li>修改記錄描述2<br>
 * <li>修改記錄描述3<br>
 * </ul>
 *
 * @author xuefl
 * @version 5.0 since 2020-01-15
 */
@RequestMapping("/consumer")
@RestController
public class ConsumerController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/get_user")
    @ApiOperation(value="get_user",httpMethod = "GET",notes="test get_user",produces = MediaType.APPLICATION_JSON_VALUE)
    public List<User> index(){
        return restTemplate.getForObject("http://provider/api/producer/get_user",
                List.class);
    }
}

以獲取用戶列表接口為例,producer為微服務(wù)a提供的接口,consumer為微服務(wù)b提供的接口,producer是真正訪問數(shù)據(jù)庫查詢用戶列表的微服務(wù),consumer通過訪問a微服務(wù)配置的application 的name:provider來調(diào)用接口,例如http://provider/api/producer/get_user;
此教程省略了mvn自動下載包的過程。

  1. 啟動DemoApplication,會自動注冊到EurekaApplication中


    啟動日志.png

    Eureka管理界面中可以看到多了一個instance


    Eureka Server管理界面.png

    打開swagger界面,調(diào)用consumer的接口,可以通過producer查詢到響應結(jié)果
    接口測試.png

我的博客即將同步至騰訊云開發(fā)者社區(qū),邀請大家一同入駐:https://cloud.tencent.com/developer/support-plan?invite_code=mmfmf1mhr7vc

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

相關(guān)閱讀更多精彩內(nèi)容

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