天天看點

微服務注冊中心Nacos入門

服務治理

服務治理的核心由三部分組成:服務提供者、服務消費者、注冊中心。在分布式系統架構中,每個微服務在啟動時,将自己的資訊存儲在注冊中心,叫做服務注冊。服務消費者從注冊中心擷取服務提供者的網絡資訊,通過該資訊調用服務,叫做服務發現。

微服務注冊中心Nacos入門

服務提供者&服務消費者

服務的提供者&服務的消費者是相對的概念:

  • 比如使用者服務調用訂單服務,那麼使用者服務是訂單服務的消費者,訂單服務是使用者服務的提供者。
  • 但是對于訂單服務調用庫存服務,那麼訂單服務就成為庫存服務消費者,庫存服務就是訂單服務的提供者。
    微服務注冊中心Nacos入門
  • 下載下傳位址: https://github.com/alibaba/Nacos/releases
tar -xzvf nacos-server-1.1.4.tar.gz      

編輯conf/application.properties檔案:

#mysql資料庫連接配接資訊,需要自己建立資料庫,sql腳本在conf/nacos-mysql.sql
server.port=8849  #3個nacos服務端口号分别為8849,8850,8851
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://192.168.1.14:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=123456      

将conf/cluster.conf.example改為conf/cluster.conf,編輯檔案:

192.168.1.5:8849
192.168.1.5:8850
192.168.1.5:8851      

依次使用

sh /bin/startup.sh

指令啟動。

nginx配置:

events{}
http {
    upstream nacos {
        server 192.168.1.5:8849;
        server 192.168.1.5:8850;
        server 192.168.1.5:8851;
    }
    server {
       listen 8848;  #用戶端通路位址
       location / {
           proxy_pass http://nacos;
        }
    }
}      

輸入

http://192.168.1.5:8848

登入nacos,使用者名nacos,密碼nacos。

微服務注冊中心Nacos入門
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-nacos-discovery</artifactId>
</dependency>      

加入注解:(以前低版本需要寫,現在其實不需要)

package com.tuling;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient  //高版本可以不寫
public class Tulingvip01MsAlibabaNacosClientOrderApplication {
 public static void main(String[] args) {
  SpringApplication.run(Tulingvip01MsAlibabaNacosClientOrderApplication.class, args);
 }
}      

寫配置檔案:

spring:
  datasource:
    druid:
      username: root
      password: 123456
      jdbcUrl: jdbc:mysql://192.168.1.14:3306/tuling-ms-alibaba?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false
      driverClassName: com.mysql.jdbc.Driver
      initialSize: 5
      minIdle: 5
      maxActive: 20
      maxWait: 60000
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      filters: stat,wall #\u914D\u7F6E\u8FC7\u6EE4\u5668
      maxPoolPreparedStatementPerConnectionSize: 20
      useGlobalDataSourceStat: true
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.1.5:8848
        #環境隔離
        namespace: 13499a23-e36e-41e7-8f8b-bd071bb8708e
        #分組隔離
        group: pay
        #cluster不相同可以調到,但是優先調本叢集
        cluster-name: BJ
  application:
    name: order-center
server:
  port: 8080      

啟動order-center和product-center服務,驗證兩個服務注冊到nacos上:

微服務注冊中心Nacos入門

服務Controller代碼

order-center通過

discoveryClient.getInstances

擷取product-center服務資訊,然後調用product-center去查詢資料庫資訊,最後傳回資訊給用戶端。

package com.tuling.controller;
import com.tuling.entity.OrderInfo;
import com.tuling.entity.ProductInfo;
import com.tuling.mapper.OrderInfoMapper;
import com.tuling.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
public class OrderInfoController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private DiscoveryClient discoveryClient;
    @RequestMapping("/selectOrderInfoById/{orderNo}")
    public Object selectOrderInfoById(@PathVariable("orderNo") String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOrderInfoById(orderNo);
        if(null == orderInfo) {
            return "根據orderNo:"+orderNo+"查詢沒有該訂單";
        }
        /**
         * 從nacos server擷取 product-info的位址
         */
        List<ServiceInstance> serviceInstanceList =  discoveryClient.getInstances("product-center");
        if(null == serviceInstanceList || serviceInstanceList.isEmpty()) {
            return "使用者微服務沒有對應的執行個體可用";
        }
        /**
         * 擷取第0個元素
         */
        String targetUri = serviceInstanceList.get(0).getUri().toString();
        ResponseEntity<ProductInfo> responseEntity= restTemplate.getForEntity(targetUri+"/selectProductInfoById/"+orderInfo.getProductNo(), ProductInfo.class);
        ProductInfo productInfo = responseEntity.getBody();
        if(productInfo == null) {
            return "沒有對應的商品";
        }
        OrderVo orderVo = new OrderVo();
        orderVo.setOrderNo(orderInfo.getOrderNo());
        orderVo.setUserName(orderInfo.getUserName());
        orderVo.setProductName(productInfo.getProductName());
        orderVo.setProductNum(orderInfo.getProductCount());
        return orderVo;
    }
    @GetMapping("/getServiceList")
    public List<ServiceInstance> getServiceList() {
        List<ServiceInstance> serviceInstanceList =  discoveryClient.getInstances("order-center");
        return serviceInstanceList;
    }
}      

調用order-center接口查詢訂單資訊:

微服務注冊中心Nacos入門