一、搭建eureka_server服務
1. 新建項目,依賴添加Cloud Discovery-->Eureka Server
2. 更換阿里雲鏡像
<repositories>
<repository>
<id>central</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<layout>default</layout>
<!-- 是否開啓發布版構件下載 -->
<releases>
<enabled>true</enabled>
</releases>
<!-- 是否開啓快照版構件下載 -->
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
3. 啓動類增加@EnableEurekaServer註解
4. 增加配置:
erver:
port: 8761
eureka:
instance:
hostname: localhost
client:
#指示此實例是否應將其信息註冊到eureka服務器以供其他服務發現,默認爲false
register-with-eureka: false
#客戶端是否獲取eureka服務器註冊表上的註冊信息,默認爲true
fetch-registry: false
service-url:
defaulrZone: http://${eureka.instance.hostname}:${server.port}/eureka/
5. 訪問:http://localhost:8761/
二、搭建商品服務
1. 新疆項目,項目依賴web-->spring web,spring cloud discovery-->eureka discovery client
2. 增加配置
server:
port: 8771
eureka:
client:
service-url:
defaulrZone: http://localhost:8761/eureka/
spring:
application:
name: product-service
3. 增加ccontroller,寫一個可響應數據的方法
4. 訪問:http://127.0.0.1:8771/api/v1/product/list
三、搭建訂單服務
1. 新建項目,項目依賴web-->spring web,spring cloud Routing-->Ribbon(一個發請求 的客戶端),spring cloud discovery-->eureka discovery client
2. 服務配置:
server:
port: 8781
eureka:
client:
service-url:
defaulrZone: http://localhost:8761/eureka/
spring:
application:
name: order-service
3. 使用Ribbon做負載均衡,由訂單服務向商品服務發起請求:
a. 啓動類注入RestTemplate的Bean
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
b. 在實現類中實現一個服務對另一個服務的調用:
Object forObject = restTemplate.getForObject("http://product-service/api/v1/product/find?id=" + productId, Object.class);
4. 另外一種Ribbon使用方式
a. 直接在實現類中引入LoadBalancerClient
@Autowired
private LoadBalancerClient loadBalancerClient;
b. 通過這個client調用
ServiceInstance choose = loadBalancerClient.choose("product-service");
String url = String.format("http://%s:%s/api/v1/product/find?id=" + productId, choose.getHost(), choose.getPort());
RestTemplate restTemplate = new RestTemplate();
Map object = restTemplate.getForObject(url, Map.class);
5. 自定義負載均衡策略
需要在調用方服務中配置
product-service:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
6. 使用Feign做負載均衡(本質還是http調用)
a. 添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
b. 啓動類新加註解:@EnableFeignClients
c. 新建一個接口
@FeignClient(name = "product-service")
public interface ProductClient {
@GetMapping("/api/v1/product/find")
String findById(@RequestParam(value = "id") int id);
}
如果原服務請求參數註解是@RequestBody,則這個接口請求註解如是,上方的註解也應該改成@PostMapping
d. 在實現類調用,拿到的是Json字符串,可以轉成對象
7. Feign調用修改超時時間
feign:
client:
config:
default:
connectTimeout: 2000
readTimeout: 2000
默認readTimeout是60s,但是由於hystrix默認是1s超時