SpringCloud如何使用Eureka實現(xiàn)服務(wù)之間的傳遞數(shù)據(jù)
相信大家最關(guān)心的肯定不是什么一大堆的破理論,然后還似懂非懂的,最關(guān)心得莫過于服務(wù)之間的參數(shù)傳遞,數(shù)據(jù)獲取。
Ok,今天就告訴大家三種微服務(wù)之間傳輸數(shù)據(jù)的方式,分別是:
1、最基本的利用Ip端口進行請求訪問接口實現(xiàn)數(shù)據(jù)的傳輸
2、使用Eureka取代Ip(硬編碼)的方式實現(xiàn)數(shù)據(jù)的傳輸
3、使用Feign更加快捷"分服務(wù)"的方式實現(xiàn)微服務(wù)之間的數(shù)據(jù)傳輸(對Feign一點不了解的暫時不用理解,就是SpringCloud的組成的一部分后期會進行詳細講解,在此處講解只是為自己mark一下)
前提:搭建好Eureka注冊中心,假設(shè)現(xiàn)在有一個訂單微服務(wù)(服務(wù)消費者),一個用戶微服務(wù)(服務(wù)提供者),然后需要訂單微服務(wù)調(diào)用用戶微服務(wù),獲取用戶的信息,并且兩個服務(wù)都能正常運行,為了方便此處使用SpringJpa的方式獲取數(shù)據(jù)。
一、使用RestTemplate+Ip方式:
1、傳遞數(shù)據(jù)大部分就是以集合和對象的形式進行傳遞,所以在這里就用集合和對象的方式為例
在用戶微服務(wù)(服務(wù)提供者)中寫好被調(diào)用的查詢方法
@RestController @RequestMapping("/user") public class UserController { @Resource private UserRepository userRepository; @GetMapping("/getallUser") public List<User> getUserPage(){ return userRepository.findAll(); } @GetMapping("/getUser") public User getUser(Long userId){ return userRepository.getOne(userId); } }
@Repository public interface UserRepository extends JpaRepository<User,Long> { }
@Entity @Table(name="TM_USER") @JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"}) public class User implements Serializable, Cloneable { @Id @GeneratedValue(strategy= GenerationType.AUTO) private Long userId; /** * 登錄名 */ @Column(name = "USER_NAME") private String userName; /** * 用戶名 */ @Column private String name; /** * 薪水 */ @Column private BigDecimal balance; /** * 年齡 get set方法已省略 自行添加 */ @Column private int age;}
Ok,服務(wù)提供者已經(jīng)寫好,下面開始編寫服務(wù)消費者
2、在訂單微服務(wù)(服務(wù)消費者)的啟動類中添加生成RestTemplate的Bean
@SpringBootApplication @EnableEurekaClient //啟用eureka客戶端 public class MicroserviceSimplecConsumerOrderServerApplication { @Bean public RestTemplate restTemplate(){ return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(MicroserviceSimplecConsumerOrderServerApplication.class, args); } }
在訂單微服務(wù)(服務(wù)消費者)配置文件yml中添加,其中l(wèi)ocalhost:9021改為用戶微服務(wù)(服務(wù)提供者的Ip和端口)
user: urlPath: http://localhost:9021
訂單服務(wù)控制層編寫,此處的User為用戶微服務(wù)的復制然后去掉@Column、@Table等注釋只是一個臨時存儲對象和數(shù)據(jù)庫沒有任何關(guān)聯(lián)
@RestController @RequestMapping("/order") public class OrderServerController { @Autowired private RestTemplate restTemplate; @Value("${user.urlPath}") private String urlPath; //獲取集合方式 @GetMapping("/allUser") private List<User> getAllUser(){ ResponseEntity<List<User>> responseEntity = restTemplate.exchange("urlPath"+/user/getallUser?", HttpMethod.GET, null, new ParameterizedTypeReference<List<User>>() {}); return responseEntity.getBody(); } //獲取單個對象方式 @GetMapping("/getUser") private User getUser(Long userId){ User user = restTemplate.getForObject("urlPath"+/user/getUser?userId="+userId,User.class); return user; } }
二、使用Eureka的方式獲取
很簡單就是直接把訂單微服務(wù)(服務(wù)消費者)OrderServerController中的userPath替換為注冊Eureka上面的服務(wù)名即可就是這么簡單。假設(shè)用戶微服務(wù)的服務(wù)名為:microservice-privider-user
spring: application: name: microservice-privider-user
然后就可以直接進行替換處理,即:
@GetMapping("/allUser") //返回集合 private List<User> getAllUser(){ ResponseEntity<List<User>> responseEntity = restTemplate.exchange("microservice-privider-user"+"/user/getallUser", HttpMethod.GET, null, new ParameterizedTypeReference<List<User>>() {}); return responseEntity.getBody(); } //返回對象 @GetMapping("/getUser") private User getUser(Long userId){ User user = restTemplate.getForObject("microservice-privider-user"+/user/getUser?userId="+userId,User.class); return user; }
Ok,使用第二種方式已經(jīng)編寫完成
使用服務(wù)名替換了固定的ip,解決了Ip硬編碼不容易維護的問題
至于第三種Feign的方式會在以后講解“Feign:聲明性Rest客戶端”的時候進行詳細講解
gitHub地址:https://github.com/mackjie/microservice-spring-cloud因為配置了RabbitMQ,所以請先閱讀ReadMe然后進行啟動項目,否則會啟動報錯
springcloud學習之Eureka Client搭建和服務(wù)間調(diào)用
Eureka Client搭建:
一、引入pom依賴
<!-- Eureka Client --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
二、啟動類推薦添加@EnableEurekaClient注解
就是如果選用的注冊中心是eureka,那么就推薦@EnableEurekaClient,
如果是其他的注冊中心(zookeeper,consul等),那么推薦使用@EnableDiscoveryClient。
三、配置文件添加:
#eureka spring.application.name=producer #注冊中心地址 eureka.client.service-url.defaultZone=http://localhost:8761/eureka #是否把自己注冊 eureka.client.register-with-eureka=true #是否搜索服務(wù)信息 eureka.client.fetch-registry=true #使用ip地址注冊 eureka.instance.prefer-ip-address=true #注冊中心列表顯示的狀態(tài) eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}
服務(wù)調(diào)用:
有兩種方式:
一、ribbon(負載均衡)+restTemplate
啟動類添加:
@Bean @LoadBalanced//負載均衡 public RestTemplate initRestTemplate() { return new RestTemplate();// } @Bean//負載均衡的規(guī)則,下面的是其中之一:隨機,還有權(quán)重,輪詢等 public IRule initIRule() { return new RandomRule(); }
RandomRule表示隨機策略
RoundRobinRule表示輪詢策略(默認)
WeightedResponseTimeRule表示加權(quán)策略
BestAvailableRule表示請求數(shù)最少策略
然后在controller中自動裝配RestTemplate后使用 restTemplate.getForObject()調(diào)用。
二、feign(推薦)
1、引入pom依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>2.1.1.RELEASE</version> </dependency>
2、啟動類添加@EnableFeignClients注解
3、創(chuàng)建一個接口,
package com.sumengnan.test.web; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; @FeignClient(name = "eureka",fallback = HtystrixEurekaFallback.class)//調(diào)用失敗后回滾執(zhí)行方法 public interface EurekaServiceApi { @GetMapping("test") String test(); }
回滾的方法:
package com.sumengnan.test.web; /** * eureka熔斷回調(diào)類 */ public class HtystrixEurekaFallback implements EurekaServiceApi { @Override public String test() { return "連接失敗,請稍后再試!"; } }
4、然后在controller中自動裝配EurekaServiceApi后使用eurekaServiceApi.test()調(diào)用。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
MybatisPlus中QueryWrapper常用方法總結(jié)
MyBatis-Plus是一個Mybatis增強版工具,在MyBatis上擴充了其他功能沒有改變其基本功能,為了簡化開發(fā)提交效率而存在,queryWrapper是mybatis plus中實現(xiàn)查詢的對象封裝操作類,本文就給大家總結(jié)了MybatisPlus中QueryWrapper的常用方法,需要的朋友可以參考下2023-07-07詳解SpringBoot讀取resource目錄下properties文件的常見方式
這篇文章主要介紹了SpringBoot讀取resource目錄下properties文件的常見方式,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02java面向?qū)ο笤O(shè)計原則之開閉原則示例解析
這篇文章主要介紹了java面向?qū)ο笤O(shè)計原則之開閉原則的示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2021-10-10