eureka註冊中心和Feign遠程調用

eureka註冊中心和Feign遠程調用

類型1:

🚅服務生產者yaml文件配置

server:
  port: ${PORT:31001} #服務端口
spring:
  application:
    name: xc-service-manage-cms #指定服務名稱
  data:
    mongodb:
      uri: mongodb://root:root@localhost:27017
      database: xc_cms
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest
    virtualHost: /
  freemarker:
    cache: false #關閉模板緩存,方便測試
    settings:
      template_update_delay: 0 #檢查模板更新延遲時間,設置爲0表示立即檢查,如果時間大於0會有緩存不方便進行模板測試
eureka:
  client:
    registerWithEureka: true #服務註冊開關
    fetchRegistry: true #服務發現開關
    serviceUrl: #Eureka客戶端與Eureka服務端進行交互的地址,多箇中間用逗號分隔
      defaultZone: ${EUREKA_SERVER:http://localhost:50101/eureka/}
  instance:
    prefer‐ip‐address: true #將自己的ip地址註冊到Eureka服務中
    ip‐address: ${IP_ADDRESS:127.0.0.1}
    instance‐id: ${spring.application.name}:${server.port} #指定實例id

🌓服務生產者啓動類

package com.xuecheng.manage_cms;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@EnableEurekaClient //表示它是一個Eureka的客戶端
@SpringBootApplication
@EntityScan("com.xuecheng.framework.domain.cms")//掃描實體類
@ComponentScan(basePackages={"com.xuecheng.api"})//掃描接口
@ComponentScan(basePackages={"com.xuecheng.framework"})//掃描common包下的類
@ComponentScan(basePackages={"com.xuecheng.manage_cms"})//掃描本項目下的所有類
public class ManageCmsApplication {
    public static void main(String[] args) {
        SpringApplication.run(ManageCmsApplication.class,args);
    }

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
    }

}

▶️消費者yml文件配置

server:
  port: 31200
spring:
  application:
    name: xc-service-manage-course
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/xc_course?characterEncoding=utf-8
      username: root
      password: root
      driverClassName: com.mysql.jdbc.Driver
      initialSize: 5  #初始建立連接數量
      minIdle: 5  #最小連接數量
      maxActive: 20 #最大連接數量
      maxWait: 10000  #獲取連接最大等待時間,毫秒
      testOnBorrow: true #申請連接時檢測連接是否有效
      testOnReturn: false #歸還連接時檢測連接是否有效
      timeBetweenEvictionRunsMillis: 60000 #配置間隔檢測連接是否有效的時間(單位是毫秒)
      minEvictableIdleTimeMillis: 300000
pagehelper:
  helper-dialect: mysql #連接在連接池的最小生存時間(毫秒)
eureka:
  client:
    registerWithEureka: true #服務註冊開關
    fetchRegistry: true #服務發現開關
    serviceUrl: #Eureka客戶端與Eureka服務端進行交互的地址,多箇中間用逗號分隔
      defaultZone: ${EUREKA_SERVER:http://localhost:50101/eureka/}
  instance:
    prefer‐ip‐address: true #將自己的ip地址註冊到Eureka服務中
    ip‐address: ${IP_ADDRESS:127.0.0.1}
    instance‐id: ${spring.application.name}:${server.port} #指定實例id
ribbon:
  MaxAutoRetries: 2 #最大重試次數,當Eureka中可以找到服務,但是服務連不上時將會重試
  MaxAutoRetriesNextServer: 3 #切換實例的重試次數
  OkToRetryOnAllOperations: false #對所有操作請求都進行重試,如果是get則可以,如果是post,put等操作沒有實現冪等的情況下是很危險的,所以設置爲false
  ConnectTimeout: 5000 #請求連接的超時時間
  ReadTimeout: 6000 #請求處理的超時時間
course‐publish:
  siteId: 5b30cba5f58b4411fc6cb1e5
  templateId: 5b345a6b94db44269cb2bfec
  previewUrl: http://www.xuecheng.com/cms/preview/
  pageWebPath: /course/detail/
  pagePhysicalPath: /course/detail/
  dataUrlPre: http://localhost:31200/course/courseview/


❎消費者啓動類

package com.xuecheng.manage_course;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author Administrator
 * @version 1.0
 **/
@EnableFeignClients //開啓FeignClients
@EnableEurekaClient //表示它是一個Eureka的客戶端
@SpringBootApplication
@EntityScan("com.xuecheng.framework.domain.course")//掃描實體類
@ComponentScan(basePackages={"com.xuecheng.api"})//掃描接口
@ComponentScan(basePackages={"com.xuecheng.manage_course"})
@ComponentScan(basePackages={"com.xuecheng.framework"})//掃描common下的所有類
public class ManageCourseApplication {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(ManageCourseApplication.class, args);
    }

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

}

消費者遠程調用接口

package com.xuecheng.manage_course.client;

import com.xuecheng.framework.client.XcServiceList;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.response.CmsPageResult;
import com.xuecheng.framework.domain.cms.response.CmsPostPageResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@FeignClient(value = XcServiceList.XC_SERVICE_MANAGE_CMS)//指定遠程調用的服務名
public interface CmsPageClient {

    //根據id查詢頁面信息,遠程調用cms請求數據
    @GetMapping("/cms/page/get/{id}")//用Getmapping標識遠程調用的http的方法類型
    public CmsPage findById(@PathVariable("id") String id);

    //添加頁面,用於課程預覽
    @PostMapping("/cms/page/save")
    public CmsPageResult saveCmsPage(@RequestBody CmsPage cmsPage);

    //一鍵發佈頁面
    @PostMapping("/cms/page/postPageQuick")
    public CmsPostPageResult  postPageQuick(CmsPage cmsPage);

}

類型2:

服務生產者yml文件配置

server:
  port: ${port:40100}
spring:
  application:
    name: xc-service-search
xuecheng:
  elasticsearch:
    hostlist: ${eshostlist:127.0.0.1:9200} #多個結點中間用逗號分隔
  course:
    index: xc_course
    type: doc
    source_field: id,name,grade,mt,st,charge,valid,pic,qq,price,price_old,status,studymodel,teachmode,expires,pub_time,start_time,end_time
  media:
    index: xc_course_media
    type: doc
    source_field: courseid,media_id,media_url,teachplan_id,media_fileoriginalname
eureka:
  client:
    registerWithEureka: true #服務註冊開關
    fetchRegistry: true #服務發現開關
    serviceUrl: #Eureka客戶端與Eureka服務端進行交互的地址,多箇中間用逗號分隔
      defaultZone: ${EUREKA_SERVER:http://localhost:50101/eureka/}
  instance:
    prefer-ip-address:  true  #將自己的ip地址註冊到Eureka服務中
    ip-address: ${IP_ADDRESS:127.0.0.1}
    instance-id: ${spring.application.name}:${server.port} #指定實例id
ribbon:
  MaxAutoRetries: 2 #最大重試次數,當Eureka中可以找到服務,但是服務連不上時將會重試,如果eureka中找不到服務則直接走斷路器
  MaxAutoRetriesNextServer: 3 #切換實例的重試次數
  OkToRetryOnAllOperations: false  #對所有操作請求都進行重試,如果是get則可以,如果是post,put等操作沒有實現冪等的情況下是很危險的,所以設置爲false
  ConnectTimeout: 5000  #請求連接的超時時間
  ReadTimeout: 6000 #請求處理的超時時間

服務生產者啓動類

package com.xuecheng.search;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;

/**
 * @author Administrator
 * @version 1.0
 **/
@EnableDiscoveryClient
@SpringBootApplication
@EntityScan("com.xuecheng.framework.domain.search")//掃描實體類
@ComponentScan(basePackages={"com.xuecheng.api"})//掃描接口
@ComponentScan(basePackages={"com.xuecheng.search"})//掃描本項目下的所有類
@ComponentScan(basePackages={"com.xuecheng.framework"})//掃描common下的所有類
public class SearchApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SearchApplication.class, args);
    }

}

消費者yml文件配置

server:
  port: ${PORT:40600}
spring:
  application:
    name: xc-service-learning
  datasource:
    druid:
      url: ${MYSQL_URL:jdbc:mysql://localhost:3306/xc_learning?characterEncoding=utf-8}
      username: root
      password: root
      driverClassName: com.mysql.jdbc.Driver
      initialSize: 5  #初始建立連接數量
      minIdle: 5  #最小連接數量
      maxActive: 20 #最大連接數量
      maxWait: 10000  #獲取連接最大等待時間,毫秒
      testOnBorrow: true #申請連接時檢測連接是否有效
      testOnReturn: false #歸還連接時檢測連接是否有效
      timeBetweenEvictionRunsMillis: 60000 #配置間隔檢測連接是否有效的時間(單位是毫秒)
      minEvictableIdleTimeMillis: 300000  #連接在連接池的最小生存時間(毫秒)
#rabbitmq配置
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest
    publisher-confirms: true
    virtual-host: /
eureka:
  client:
    registerWithEureka: true #服務註冊開關
    fetchRegistry: true #服務發現開關
    serviceUrl: #Eureka客戶端與Eureka服務端進行交互的地址,多箇中間用逗號分隔
      defaultZone: ${EUREKA_SERVER:http://localhost:50101/eureka/,http://localhost:50102/eureka/}
  instance:
    prefer-ip-address:  true  #將自己的ip地址註冊到Eureka服務中
    ip-address: ${IP_ADDRESS:127.0.0.1}
    instance-id: ${spring.application.name}:${server.port} #指定實例id
ribbon:
  MaxAutoRetries: 2 #最大重試次數,當Eureka中可以找到服務,但是服務連不上時將會重試,如果eureka中找不到服務則直接走斷路器
  MaxAutoRetriesNextServer: 3 #切換實例的重試次數
  OkToRetryOnAllOperations: false  #對所有操作請求都進行重試,如果是get則可以,如果是post,put等操作沒有實現冪等的情況下是很危險的,所以設置爲false
  ConnectTimeout: 5000  #請求連接的超時時間
  ReadTimeout: 6000 #請求處理的超時時間

消費者啓動類

package com.xuecheng.learning;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author Administrator
 * @version 1.0
 * @create 2018-07-14 11:11
 **/
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
@EntityScan(value = {"com.xuecheng.framework.domain.learning","com.xuecheng.framework.domain.task"})//掃描實體類
@ComponentScan(basePackages={"com.xuecheng.api"})//掃描接口
@ComponentScan(basePackages={"com.xuecheng.learning"})//掃描接口
@ComponentScan(basePackages={"com.xuecheng.framework"})//掃描common下的所有類
public class LearningApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(LearningApplication.class, args);
    }

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

}

消費者遠程調用接口

package com.xuecheng.learning.client;

import com.netflix.loadbalancer.ServerList;
import com.xuecheng.framework.client.XcServiceList;
import com.xuecheng.framework.domain.course.TeachplanMediaPub;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = XcServiceList.XC_SERVICE_SEARCH)
public interface CourseSearchClient {

    //根據課程計劃id查詢課程媒資
    @GetMapping(value="/search/course/getmedia/{teachplanId}")
    public TeachplanMediaPub getmedia(@PathVariable("teachplanId") String teachplanId);

}

rk.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = XcServiceList.XC_SERVICE_SEARCH)
public interface CourseSearchClient {

//根據課程計劃id查詢課程媒資
@GetMapping(value="/search/course/getmedia/{teachplanId}")
public TeachplanMediaPub getmedia(@PathVariable("teachplanId") String teachplanId);

}


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