Spring Cloud 微服務一:Consul注冊中心


  1. Consul介紹  
    •  Consul is a service mesh solution providing a full featured control plane with service discovery, configuration, and segmentation functionality. Each of these features can be used individually as needed, or they can be used together to build a full service mesh. Consul requires a data plane and supports both a proxy and native integration model. Consul ships with a simple built-in proxy so that everything works out of the box, but also supports 3rd party proxy integrations such as Envoy. 以上是官網介紹,大概意思是:Consul是一個service mesh 解決方案,包含服務發現、配置、外部服務;這些功能可以按需單獨使用。
    • Consul核心能力包括:服務發現、健康檢查、KV存儲、安全通信、多數據中心。本章主要使用服務發現功能。Consul官網:https://www.consul.io/
  2. 2. Consul安裝有兩種方式:原生安裝,docker安裝,本例主要采用docker方式
    •   docker安裝:安裝方法參考:https://github.com/JensenShao/consul 。以單機模式安裝Consul,第一步,獲取鏡像:docker pull wdijkerman/consul;第二步,docker宿主機上創建文件
      {
      	"data_dir": "/consul/data", "log_level": "INFO", "client_addr": "0.0.0.0", "ports": { "dns": 53 }, "ui": true, "server": true, "bootstrap_expect": 1, "disable_update_check": true };第三步,啟動鏡像:docker run -u root -p 8400:8400 -p 8500:8500 -p 8600:53/udp -h server1 -v /root/shaozj/consul/config/my_config.json:/consul/config/my_config.json:ro  --privileged=true wdijkerman/consul;更多參數配置可參考上面鏈接地址。
    • 原生安裝方式參考:https://www.consul.io/docs/install/index.html
    •  
    3.spring 集成,springcloud對Consul的基本操作進行了封裝,我們可以方便地使用consul的功能,本文中主要是使用consul的服務發現功能,客戶端使用Springcloud feign做http客戶端以及負載均衡,以用戶管理為例描述服務發現功能。
    • 環境准備:本機安裝Maven,JDK1.8,Intellij Idea環境;spring環境:spring boot使用2.0.8.RELEASE版本,spring cloud使用Finchley.SR2, 具體版本間的兼容關系請參考spring官網:http://spring.io/projects/spring-cloud,里面有明確說明
    • 創建工程骨架:創建父工程parent,創建三個module:user-api,user-service,user-consumer;其中user-api中定義了服務接口,user-service和user-consumer都會依賴這個接口;user-service是對於user-api中接口的實現;user-consumer主要通過feign來調用服務
    • 編寫user-api代碼:首先,由於api工程中會用到web的一些注解,需要pom中依賴spring-boot-starter-web。創建實體類User.java, 屬性有id,name,創建接口UserService:
      public interface UserService{
          @GetMapping("/all")
          List<User> getAllUsers();
      }

      這樣一個接口就完成了

      • 接下來編寫user-service,主要是對user-api接口的實現,是服務的提供方。首先,pom中需要依賴user-api,另外需要依賴spring cloud consul服務發現組件:spring-cloud-starter-consul-discovery。創建UserService實現類UserServiceImpl:
        @RestController
        public class UserServiceImpl implements UserService{
            @Override
            public List<User> getAllUsers(){
                // 模擬DAO
                List<User> userList = new ArrayList<>();
                userList.add(new User(1, "consul"));
                userList.add(new User(1, "feign"));
                
                return userList;
            }
        }

        此處還需要添加一個springboot的啟動類UserServiceApplication用於啟動,

        @SpringBootApplication
        @EnableDiscoveryClient
        public class UserServiceApplication{
            public static void main(String[] args){
                SpringApplication.run(UserServiceApplication.class, args);
            }
        }

        其中@EnableDiscoveryClient注解作用是讓注冊中心能夠發現並掃描該服務。最后添加spring配置application.yml:

        spring:
        	application:
        		name: user-service
        	cloud:
                consul:
                    host: 127.0.0.1
                    port: 8500
                    discovery:
                        register: true
                        hostname: 127.0.0.1
                        
        server:
            port: 10086

        其中register表示該工程下的服務會注冊到注冊中心

    • 實現user-consumer,該工程主要是服務的調用方。同樣先在pom中添加依賴包:user-api, 同時需要依賴spring cloud feign:spring-cloud-starter-openfeign, 還需要依賴:spring-cloud-starter-consul-discovery作為http客戶端。首先定義一個接口UserServiceClient繼承UserService(此處為feign的使用方式):
      //其中@FeignClient注解表示要調用的微服務
      @FeignClient(value="user-service") public UserServiceClient extends UserService{}

      創建UserController調用服務:

      @RestController
      public class UserController{
          //自動注入feign客戶端
          @Autowired
          private UserServiceClient userServiceClient;
          
          @GetMapping("/users")
          public List<User> getAllUsers(){
              //調用微服務
              return userServiceClient.getAllUsers();
          }
      }

      創建springboot啟動類UserConsumerApplication:

      //@EnableFeignClients表示啟用feign客戶端,通過此注解可以使用feign
      @EnableFeignClients
      @SpringBootApplication
      public class UserConsumerApplication{
          public static void main(String[] args){
              SpringApplication.run(UserConsumerApplication.class, args);
          }
      }

      創建spring配置文件application.yml:

      spring:
          application:
              name: user-consumer
          cloud:
              consul:
                  host: 127.0.0.1
                  port: 8500
                  discovery:
                  # false表示該工程下的服務不會被注冊
                      register: false
                      
      server:
          port: 10080

       

    • 分別啟動user-service,user-consumer應用,在瀏覽器訪問:http://localhost:10080/users,能夠返回用戶列表即表示成功


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM