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
    

猜你喜欢

转载自blog.csdn.net/sdkdeveloper/article/details/104530344