spring boot/cloud in action

  • spring boot介紹

  • maven依賴

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.ljb</groupId>
	<artifactId>spring-boot</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<properties>
		<java.version>1.8</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outoutEncoding>UTF-8</project.reporting.outoutEncoding>
	</properties>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.7.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<!-- using spring boot without parent pom -->
	<!-- 
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-dependencies</artifactId>
				<version>2.1.12.RELEASE</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
	 -->
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Brixton.SR5</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka-server</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-feign</artifactId>
		</dependency>
		<!-- package as an executable jar -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
		</dependency>
		<!-- for upgrade -->
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>
  • 啓動類
@SpringBootApplication
public class HelloApplication {

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

}
  • 示例代碼
@RestController
public class HelloController {

  @RequestMapping("/helloworld")
  public String index() {
    return "Hello World!";
  }
}
  • application.yaml配置文件
server:
  port: ${random.int[10000,19999]} #使用隨機數
  • 測試代碼
import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
//省略一部分import

@RunWith(SpringJUnit4ClassRunner.class)//引入Spring對JUnit4的支持
@SpringApplicationConfiguration(classes = HelloApplication.class)//指定SpringBoot的啓動類
@WebAppConfiguration //開啓Web應用的配置,用於模擬ServletContext。
public class TestHelloController {

  private MockMvc mvc;//用於模擬調用Controller的接口發起請求

  @Test
  public void hello() throws Exception {
    mvc.perform(MockMvcRequestBuilders.get("/helloworld").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().string(equalTo("Hello World test auto restartddfddf!")));
  }

}

  • actuator提供的一些接口
    actuator是環境變量,垃圾收集信息,內存信息,線程池信息等收集的一個標準化實現框架,添加maven依賴即可,開箱即用。
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
  • @Value的使用
    說明:@Value是spring 本身提供的功能
  1. application.yaml文件中添加
book:
  name: spring cloud
  author: ljb
  1. 添加對應的實體類
@Component
public class BookEntity {
  

  @Value("${book.name}")
  private String name;
  @Value("${book.author}")
  private String author;
  
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getAuthor() {
    return author;
  }
  public void setAuthor(String author) {
    this.author = author;
  }
}

  • 控制層進行依賴注入
@RestController
public class HelloController {

  @Autowired
  private BookEntity bookEntity;
  
  @RequestMapping("/book")
  public BookEntity bookMsg() {
    return bookEntity;
  }
}

在spring boot中,多環境配置的文件名需滿足application-{profile}.yaml的格式,其中{profile}對應你的環境標識,包含如下三種:

  • application-dev.yaml 開發環境
  • application-test.yaml 測試環境
  • application-prod.yaml 生產環境

若在application.yaml中配置spring.profiles.active=test就會加載application-test.yaml的配置文件

  • 自動重啓
    在激活了開發着工具後,Classpath裏對任何文件做任何修改都會出發應用程序重啓。爲了讓重啓速度夠快,不會修改的類(比如第三方JAR文件裏的類)都加載到了基礎類加載器裏,而應用程序的代碼則會加載到一個單獨的重啓類加載器裏。檢測到變更時,只有重啓類加載器重啓。有些Classpath裏的資源變更後不需要重啓應用程序,像Thymeleaf這樣的試圖模板可以直接編輯,不用重啓應用程序。在static或public裏的靜態資源也不用重啓應用程序,所以spring boot開發着工具會在重啓時排除掉如下目錄:/META-INFO/resources、/resources、/resources、/static、/public和/templates。
    可以設置spring-devtools.restart.exclude屬性來覆蓋默認的重啓排除目錄。

  • 開啓自動重啓

    <dependency>   
    	<groupId>org.springframework.boot</groupId>   
    	<artifactId>spring-boot-devtools</artifactId> 
    </dependency>
    
  • 命令模式
    將來自客戶端的請求封裝給成一個對象,從而讓你可以使用不同的請求對客戶端進行參數化。它可以被用於實現“行爲請求者”與“行爲實現着”的解耦,以便使兩者可以適應變化。

  • Eureka
    使用eureka進行服務註冊發現

    @EnableEurekaServer
    @SpringBootApplication
    public class EurekaServerApplication {
      public static void main(String[] args) {
        new SpringApplicationBuilder(EurekaServerApplication.class).web(true).run(args);
      }
    
    }
    
  • Eureka配置文件

    server:
      port: 1111
    eureka:
      instance:
        hostname: localhost
      client:
        register-with-eureka: false #不向註冊中心註冊自己
        fetch-registry: false  #不去拉去服務
        serviceUrl:
          defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/  
    
  • 使用ribbon負載調用

    <dependency>
    	<groupId>org.springframework.cloud</groupId>
    	<artifactId>spring-cloud-starter-ribbon</artifactId>
    </dependency>
    
  • clinet端調用代碼

    @SpringBootApplication
    @EnableAutoConfiguration
    @EnableDiscoveryClient
    public class ClientApplication {
    
      @Bean
      @LoadBalanced
      RestTemplate restTemplate() {
        return new RestTemplate();
      }
    
      public static void main(String[] args) {
        SpringApplication.run(ClientApplication.class, args);
      }
    
    }
    
    @RestController
    public class ClinetController {
    
      @Autowired
      private RestTemplate restTemplate;
    
      @RequestMapping(value = "/ribbon-consumer", method = RequestMethod.GET)
      public int printInstanceId() {
        return restTemplate.getForEntity("http://SERVER/server", Integer.class).getBody();
      }
    }
    
    • client配置文件
    spring:
      application:
        name: CLIENT
    server:
      port: 8085
    eureka:  
      client:
        serviceUrl:
          defaultZone: http://localhost:1111/eureka/ 
    
  • 服務端代碼

    @SpringBootApplication
    @EnableAutoConfiguration
    @EnableDiscoveryClient
    public class ServertApplication {
        public static void main(String[] args) {
            SpringApplication.run(ServertApplication.class, args);
        }
    }
    
    @RestController
    public class ServerController {
    
      @Autowired
      private DiscoveryClient client;
      
      @RequestMapping(value = "/server", method = RequestMethod.GET)
      public int printInstanceId() {
        ServiceInstance service = client.getLocalServiceInstance();
        return service.getPort();
      }
    }
    
    • 服務端配置文件
    spring:
      application:
        name: SERVER
    server:
      port: 8092
    eureka:  
      client:
        serviceUrl:
          defaultZone: http://localhost:1111/eureka/
        healthcheck:
          enabled: true
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章