SpringBoot和SpringCloud的学习与使用
本文是基于SpringBoot 2.0.4.release环境,学习和使用SpringBoot:
- SpringBoot 2.0.4.release
一、SpringBoot介绍
(1)什么是SpringBoot
Spring Boot是一个用来搭建Spring应用的脚手架,为了简化复杂的配置,解决混乱的依赖关系。
(2)SpringBoot的特点
a. 可以创建独立的Spring应用程序,并且基于其Maven或Gradle插件,可以创建可执行的JARs和WARs
b. 内嵌Tomcat或Jetty等Servlet容器;
c. 提供自动配置的“starter”项目对象模型(POMS)以简化Maven配置;
d. 尽可能自动配置Spring容器;
e. 提供准备好的特性,如指标、健康检查和外部化配置;
f. 绝对没有代码生成,不需要XML配置
二、SpringBoot使用
(1)属性注入配置文件
- application.yaml
inspur:
sms:
accessId: 123456
accessName: jack
chaoyue:
system:
id: 123456
name: jack
- SmsProperties.java
@Data
@ConfigurationProperties(prefix="inspur.sms")
public class SmsProperties{
private String accessId;
private String accessName;
}
- SystemProperties.java
@Data
@ConfigurationProperties(prefix="chaoyue.system")
public class SystemProperties{
private String id;
private String name;
}
- SmsService.java
@EnableConfigurationProperties({SmsProperties.class, SystemProperties.class})
public class SmsService{
@Autowired
private SmsProperties smsProperties;
@Autowired
private SystemProperties systemProperties;
public void test(){
System.out.println(smsProperties.getAccessName());
System.out.println(systemProperties.getName());
}
}
(1)拦截器
- MyInterceptor.java
@Slf4j
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("前置方法正在执行");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("后置方法正在执行");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("完成方法正在执行");
}
}
- MyInerceptorConfig.java
@Configuration
public class MyInerceptorConfig implements WebMvcConfigurer {
@Autowired
private MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}
三、SpringCloud介绍
(1)什么是SpringCloud
Spring Boot是一个用来搭建Spring应用的脚手架,为了简化复杂的配置,解决混乱的依赖关系。
(2)SpringCloud的特点
a. 可以创建独立的Spring应用程序,并且基于其Maven或Gradle插件,可以创建可执行的JARs和WARs
b. 内嵌Tomcat或Jetty等Servlet容器;
c. 提供自动配置的“starter”项目对象模型(POMS)以简化Maven配置;
d. 尽可能自动配置Spring容器;
e. 提供准备好的特性,如指标、健康检查和外部化配置;
f. 绝对没有代码生成,不需要XML配置
二、SpringCloud使用
(1)注册中心Eureka
注册中心
- Eureka注册中心的EurekaServiceApplication.java
@SpringBootApplication
@EnableEurekaServer
public class EurekaServiceApplication
{
public static void main(String[] args) {
SpringApplication.run(EurekaServiceApplication.class, args);
}
}
- Eureka注册中心的application.yaml
server:
port: 8761
spring:
application:
name: eureka-service
eureka:
client:
service-url:
defaultZone: http://192.168.0.198:8761/eureka, http://192.168.0.198:8762/eureka
fetch-registry: false
server:
enable-self-preservation: true # 开启自我保护状态
eviction-interval-timer-in-ms: 10000 # 实现剔除时间
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
服务提供方
- 服务提供方的ProviderApplication.java
@SpringBootApplication
@MapperScan("com.chaoyue.leyou.mapper")
@EnableDiscoveryClient
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
- 服务提供方的application.yaml
server:
port: 8081
spring:
application:
name: service-provider
datasource:
url: jdbc:mysql://localhost:3306/heima
password: 123456
username: root
driver-class-name: com.mysql.jdbc.Driver
mybatis:
type-aliases-package: com.chaoyue.leyou.pojo
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8761/eureka, http://127.0.0.1:8762/eureka
instance:
lease-renewal-interval-in-seconds: 5 # 服务续约时间间隔
lease-expiration-duration-in-seconds: 15 # 服务失效时间间隔
prefer-ip-address: true
ip-address: 127.0.0.1
服务消费方
- 服务消费方的ConsumerApplication.java
@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerApplication {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
};
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
- 服务消费方的UserController.java
@RestController
public class UserController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("consumer/user/{id}")
public User getUserById(@PathVariable("id") Long id) {
List<ServiceInstance> instances = discoveryClient.getInstances("SERVICE-PROVIDER");
ServiceInstance instance = instances.get(0);
String host = instance.getHost();
int port = instance.getPort();
return this.restTemplate.getForObject("http://" + host + ":" + port + "/user/" + id, User.class);
}
}
- 服务消费方的application.yaml
server:
port: 8083
spring:
application:
name: service-consumer
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8761/eureka, http://127.0.0.1:8762/eureka
registry-fetch-interval-seconds: 5 # 拉取服务列表时间间隔
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
(2)负载均衡器Ribbon
服务消费方
- 服务消费方的ConsumerApplication.java
@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
};
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
- 服务消费方的UserController.java
@RestController
public class UserController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("consumer/user/{id}")
public User getUserById(@PathVariable("id") Long id) {
return this.restTemplate.getForObject("http://service-provider/user/" + id, User.class);
}
}
- 服务消费方的application.yaml
server:
port: 8083
spring:
application:
name: service-consumer
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8761/eureka, http://127.0.0.1:8762/eureka
registry-fetch-interval-seconds: 5 # 拉取服务列表时间间隔
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
service-provider:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
(3)熔断器Hystrix
服务消费方
- 服务消费方的ConsumerApplication.java
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class ConsumerApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
};
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
- 服务消费方的UserController.java
@RestController
public class UserController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("consumer/user/{id}")
@HystrixCommand(fallbackMethod = "getUserByIdFallback")
public User getUserById(@PathVariable("id") Long id) {
return this.restTemplate.getForObject("http://service-provider/user/" + id, User.class);
}
public User getUserByIdFallback(Long id) {
User user = new User();
return user;
}
}
(4)网关Zuul
- ZuulServiceApplication.java
@SpringBootApplication
@EnableZuulProxy
@EnableDiscoveryClient
public class ZuulServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulServiceApplication.class, args);
}
}
- application.yaml
server:
port: 5555
spring:
application:
name: zuul-service
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8761/eureka, http://127.0.0.1:8762/eureka
registry-fetch-interval-seconds: 5
instance:
lease-renewal-interval-in-seconds: 5 # 服务续约时间间隔
lease-expiration-duration-in-seconds: 15 # 服务失效时间间隔
prefer-ip-address: true
ip-address: 127.0.0.1
zuul:
routes:
service-consumer: /service-consumer/**
prefix: /api
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 6000