SpringCloud第三節內容精簡,Eureka集羣和提供者集羣

在這裏先說個坑,因爲新建模塊搞錯了,刪除後重新創建發現無法識別java文件,resource,yml燈文件。

打開根模塊的.idea下的misc.xml。打開misc.xml後,可以看到以下標籤內容。gdutdemo-mapper這個模塊名被添加進ignoreFiles的集合中。只需要刪除option內的內容即可。

 

 

先修改host文件

 

先修改eureka的集羣設置

7001指向7002,7002指向 7001,互相註冊

server:
  port: 7001


eureka:
  instance:
    hostname: eureka7001.com #eureka服務端的實例名稱
  client:
    register-with-eureka: false     #false表示不向註冊中心註冊自己。
    fetch-registry: false     #false表示自己端就是註冊中心,我的職責就是維護服務實例,並不需要去檢索服務
    service-url:
      #集羣指向其它eureka
      defaultZone: http://eureka7002.com:7002/eureka/

 

提供者也要修改application.yml。還可以修改別名:eureka:instance: instance-id: payment8001。以及prefer-ip-address: true #訪問路徑顯示 IP

server:
  port: 8001

spring:
  application:
    name: cloud-payment-service
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 當前數據源操作類型
    driver-class-name: org.gjt.mm.mysql.Driver              # mysql驅動包
    url: jdbc:mysql://localhost:3306/db2019?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: root

eureka:
  client:
    #表示是否將自己註冊進EurekaServer默認爲true。
    register-with-eureka: true
    #是否從EurekaServer抓取已有的註冊信息,默認爲true。單節點無所謂,集羣必須設置爲true才能配合ribbon使用負載均衡
    fetchRegistry: true
    service-url:
      #單機版
      #defaultZone: http://localhost:7001/eureka
      # 集羣版
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka

mybatis:
  mapperLocations: classpath:mapper/*.xml
  type-aliases-package: com.atguigu.springcloud.entities    # 所有Entity別名類所在包

 

最後是消費者,也要先修改yml文件

server:
  port: 80

spring:
  application:
    name: cloud-order-service

eureka:
  client:
    #表示是否將自己註冊進EurekaServer默認爲true。
    register-with-eureka: true
    #是否從EurekaServer抓取已有的註冊信息,默認爲true。單節點無所謂,集羣必須設置爲true才能配合ribbon使用負載均衡
    fetchRegistry: true
    service-url:
      #單機
      #defaultZone: http://localhost:7001/eureka
      # 集羣
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka  # 集羣版

修改配置類,必須加註解,賦予resttemplate負載均衡的能力,才能讓他輪詢

@Configuration
public class ApplicationContextConfig {

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

修改控制器

@Slf4j
@RestController
public class OrderController {

    //public static final String PAYMENT_URL = "http://localhost:8001";
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章