Springcloud入門學習筆記
1. 專案初始化配置
1. 1. 新建maven工程
使用idea創建maven專案
1. 2. 在parent專案pom中匯入以下依賴
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
</parent>
<properties>
<spring.cloud-version>Hoxton.SR8</spring.cloud-version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring.cloud-version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
2. Eureka使用
2. 1. 創建子module,命名為eureka-server
2. 2. 在eureka-server中添加以下依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2. 3. 在application.yml中添加以下配置
server:
port: 8900 #應用的埠號
eureka:
client:
service-url:
defaultZone: http://user:123@localhost:8900/eureka #eureka服務的的注冊地址
fetch-registry: false #是否去注冊中心拉取其他服務地址
register-with-eureka: false #是否注冊到eureka
spring:
application:
name: eureka-server #應用名稱 還可以用eureka.instance.hostname = eureka-server
security: #配置自定義Auth賬號密碼
user:
name: user
password: 123
2. 4. 在啟動類上架注解
@SpringBootApplication
@EnableEurekaServer
在啟動類中加入以下方法,防止spring的Auth攔截eureka請求
@EnableWebSecurity
static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().ignoringAntMatchers("/eureka/**");
super.configure(http);
}
}
2. 5. 創建module名為provider-user為服務提供者
2. 5. 1. 在pom中添加以下依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2. 5. 2. application.yml配置
server:
port: 7900 #程式啟動入口
spring:
application:
name: provider-user #應用名稱
eureka:
client:
service-url:
defaultZone: http://user:123@${eureka.instance.hostname}:${server.port}/eureka/
2. 5. 3. 啟動類加注解
@SpringBootApplication
@EnableEurekaClient
Controller相關代碼如下:
@RestController
public class UserController {
@GetMapping (value = "https://www.cnblogs.com/user/{id}")
public User getUser(@PathVariable Long id){
User user = new User();
user.setId(id);
user.setDate(new Date());
System.out.println("7900");
return user;
}
@PostMapping (value = "https://www.cnblogs.com/user")
public User getPostUser(@RequestBody User user){
return user;
}
}
2. 6. 創建module名為consumer-order為服務提供者
2. 6. 1. pom依賴同服務提供者
2. 6. 2. application.yml配置
server:
port: 8010
spring:
application:
name: consumer-order
eureka:
client:
serviceUrl:
defaultZone: http://user:123@${eureka.instance.hostname}:${server.port}/eureka/
2. 6. 3. 啟動類
@SpringBootApplication
@EnableEurekaClient
public class ConsumerApp
{
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main( String[] args )
{
SpringApplication.run(ConsumerApp.class,args);
}
}
2. 6. 4. Controller層代碼
@RestController
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@GetMapping (value = "https://www.cnblogs.com/order/{id}")
public User getOrder(@PathVariable Long id){
//獲取資料
User user = new User();
user.setId(id);
user.setDate(new Date());
user = restTemplate.getForObject("http://provider-user:7900/user/"+id,User.class);
return user;
}
}
2. 7. 啟動應用
分別啟動Eureka-server、provider-user、consumer-order三個服務
2. 8. 訪問地址
http://localhost:8900就可以看到兩個服務已經注冊到eureka注冊中心上了
2. 9. eureka高可用配置
兩個節點
#高可用配置,兩個節點
spring:
application:
name: eureka-server-ha
profiles:
active: peer1
eureka:
client:
serviceUrl:
defaultZone: https://peer1/eureka/,http://peer2/eureka/
---
server:
port: 8901
spring:
profiles: peer1
eureka:
instance:
hostname: peer1
---
server:
port: 8902
spring:
profiles: peer2
eureka:
instance:
hostname: peer2
三個節點
#高可用配置,三個
spring:
application:
name: eureka-server-ha
profiles:
active: peer3
eureka:
client:
serviceUrl:
defaultZone: http://peer1:8901/eureka/,http://peer2:8902/eureka/,http://peer3:8903/eureka/
---
spring:
profiles: peer1
eureka:
instance:
hostname: peer1
server:
port: 8901
---
spring:
profiles: peer2
eureka:
instance:
hostname: peer2
server:
port: 8902
---
spring:
profiles: peer3
eureka:
instance:
hostname: peer3
server:
port: 8903
3. Ribbon的使用入門
3. 1. 方式一(默認)
輪詢規則
在啟動類中restTemplate()方法加入注解@LoadBalanced
RestTemplate 是由 Spring Web 模塊提供的工具類,與 SpringCloud 無關,是獨立存在的,因 SpringCloud 對 RestTemplate 進行了一定的擴展,所以 RestTemplate 具備了負載均衡的功能
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
在啟動類上加注解
@RibbonClient(name = "provider-user")
3. 2. 方式二(組態檔自定義)
在application.yml中加入以下配置
#使用組態檔方式實作負載均衡,優先級,組態檔>注解或java代碼配置>cloud默認配置
provider-user:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
3. 3. 方式三(Java代碼自定義)
自定義一個配置類,回傳規則
@RibbonClient(name = "provider-user",configuration = RibbonConfiguration.class)
public class RibbonConfiguration {
@Bean
public IRule getRule(){
return new RandomRule();
}
}
4. Feign學習
什么是feign,是宣告式的webservice客戶端,解決遠程呼叫,支持JAX-RS,即RestFulWebService
4. 1. 引入依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
4. 2. 使用注解@FeignClient撰寫feign呼叫的客戶端介面
@FeignClient("provider-user")
public interface UserFeignClient {
@RequestMapping (value = "https://www.cnblogs.com/user/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable Long id);
@RequestMapping (value = "https://www.cnblogs.com/user", method = RequestMethod.POST)
public User postUser(@RequestBody User user);
}
4. 3. 在啟動類加注解@EnableFeignClients
4. 4. Controller層的呼叫方法
@Autowired
private UserFeignClient userFeignClient;
@GetMapping (value = "https://www.cnblogs.com/user/{id}")
public User getUser(@PathVariable Long id){
//獲取資料
return this.userFeignClient.getUser(id);
}
@GetMapping (value = "https://www.cnblogs.com/user")
public User postUser(User user){
return this.userFeignClient.postUser(user);
}
5. hystrix學習
hystrix是Netflix的一個類別庫,在微服務中,具有多層服務呼叫,主要實作斷路器模式的類別庫
5. 1. 引入依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
5. 2. 在啟動類上加注解
@EnableCircuitBreaker
-
- 在Controller層類的方法上加注解,并撰寫退回方法,需同名
@HystrixCommand(fallbackMethod = "findByIdFallBack")
public User getOrder(@PathVariable Long id){
//獲取資料
User user = new User();
user.setId(id);
user.setDate(new Date());
user = restTemplate.getForObject("http://provider-user/user/"+id,User.class);
System.out.println(Thread.currentThread().getId());
return user;
}
public User findByIdFallBack(Long id){
System.out.println(Thread.currentThread().getId());
User user = new User();
user.setId(1L);
return user;
}
6. springboot的健康監控actuator
actuator主要用于服務健康監控,springboot 1.X和2.x有所不同,本次為2.X
6. 1. 引入依賴包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
6. 2. 配置
#健康監控配置
management:
endpoint:
health:
show-details: always #是否健康監控顯示細節
endpoints:
web:
exposure:
include: hystrix.stream #hystrix保護機制,不直接暴露監控狀態
base-path: / #暴露的端點鏈接
6. 3. 訪問
1.X版本
localhost:8080/health
2.X版本
localhost:8080/actuator/health
7. feign配合Hystrix使用
7. 1. 組態檔
feign:
hystrix:
enabled: true # 總開關,可以通過java單獨控制client
7. 2. 啟動類注解
@EnableFeignClients
7. 3. 控制層
@RestController
public class OrderFeignController {
@Autowired
private UserFeignClient userFeignClient;
@Autowired
private UserFeignNotHystrixClient userFeignNotHystrixClient;
@GetMapping (value = "https://www.cnblogs.com/order/{id}")
public User getUser(@PathVariable Long id){
//獲取資料
return userFeignClient.getUser(id);
}
/**
* 測驗Feign客戶端單獨控制
* @param id
* @return
*/
@GetMapping(value = "https://www.cnblogs.com/user/{id}")
public User getUserNotHystrix(@PathVariable Long id){
//獲取資料
return userFeignNotHystrixClient.getUserNotHystrix(id);
}
}
7. 4. 兩個FeignClient
一個加了configuration一個沒有,加了可以通過注解重寫feignBuilder方法單獨控制,默認是回傳HystrixFeignBuilder
@FeignClient(name = "provider-user", fallback = HystrixClientFallback.class)
public interface UserFeignClient {
@RequestMapping (value = "https://www.cnblogs.com/user/{id}", method = RequestMethod.GET)
User getUser(@PathVariable Long id);
}
@Component
public class HystrixClientFallback implements UserFeignClient{
@Override
public User getUser(Long id) {
System.out.println(Thread.currentThread().getId());
User user = new User();
user.setId(1L);
return user;
}
}
@FeignClient(name = "provider-user1",configuration = ConfigurationNotHystrix.class,fallback = HystrixClientNotHystrixFallback.class)
public interface UserFeignNotHystrixClient {
@RequestMapping (value = "https://www.cnblogs.com/user/{id}", method = RequestMethod.GET)
User getUserNotHystrix(@PathVariable Long id);
}
@Component
public class HystrixClientNotHystrixFallback implements UserFeignNotHystrixClient{
@Override
public User getUserNotHystrix(Long id) {
System.out.println(Thread.currentThread().getId());
User user = new User();
user.setId(1L);
return user;
}
}
7. 5. 配置類
@Configuration
public class ConfigurationNotHystrix {
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder(){
return Feign.builder();
}
}
7. 6. 獲取例外資訊代碼
@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)
protected interface HystrixClient {
@RequestMapping(method = RequestMethod.GET, value = "https://www.cnblogs.com/hello")
Hello iFailSometimes();
}
@Component
static class HystrixClientFallbackFactory implements FallbackFactory<HystrixClient> {
@Override
public HystrixClient create(Throwable cause) {
return new HystrixClient() {
@Override
public Hello iFailSometimes() {
return new Hello("fallback; reason was: " + cause.getMessage());
}
};
}
}
持續更新中
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/165326.html
標籤:Java
