springBoot与springCloud学习总结(第二章)
1.了解springCloud
1.1.什么是springCloud
SpringCloud是Spring旗下的项目之一,官网地址:http://projects.spring.io/spring-cloud/
Spring最擅长的就是集成,把世界上最好的框架拿过来,集成到自己的项目中。
SpringCloud也是一样,它将现在非常流行的一些技术整合到一起,实现了诸如:配置管理,服务发现,智能路由,负载均衡,熔断器,控制总线,集群状态等等功能。其主要涉及的组件包括:
Netflix:
- Eureka:注册中心
- Zuul:服务网关
- Ribbon:负载均衡
- Feign:服务调用
- Hystrix:熔断器
2.搭建微服务场景
2.1.创建父工程
微服务中需要同时创建多个项目,我先创建一个父工程,然后后续的工程都以这个工程为父,实现maven的聚合。这样可以在一个窗口看到所有工程,模拟微服务场景。在实际开发中,每个微服务都是独立的工程。
然后编写pom.xml依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
<mapper.starter.version>2.1.4</mapper.starter.version>
<mysql.version>8.0.27</mysql.version>
<pageHelper.starter.version>1.2.5</pageHelper.starter.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- springCloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- 通用Mapper启动器 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>${mapper.starter.version}</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
2.2.服务提供者
新建一个项目,对外提供查询用户的服务
2.2.1.创建module(userService)
添加依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
</dependency>
</dependencies>
2.2.2.编写代码
yml:
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/makeke
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
启动类:
@SpringBootApplication
public class userServiceApplication {
public static void main(String[] args) {
SpringApplication.run(userServiceApplication.class,args);
}
}
实体类:
@Table(name = "user")
@Data
public class User {
@Id
@KeySql(useGeneratedKeys = true)
private String id;
private String name;
private String age;
private String mate;
private String job;
}
mapper:
public interface UserMapper extends Mapper<User> {
}
service:
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public User selectById(String id) {
return userMapper.selectByPrimaryKey(id);;
}
}
controller:
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
@GetMapping("/{id}")
public User selectById(@PathVariable("id") String id){
return userService.selectById(id);
}
}
项目结构:
启动测试:
启动项目报错,没有找到mapper,是因为没有对mapper包进行扫描,在启动类上加上注解@MapperScan(“com.makeke.mapper”)之后再次启动项目:
2.3.服务调用者
2.3.1.创建module(userConsumer)
添加依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2.3.2.编写代码
启动类
@SpringBootApplication
public class UserCustomerApplication {
public static void main(String[] args) {
SpringApplication.run(UserCustomerApplication.class,args);
}
//创建restTemplate对象,用做httpClient远程调用
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
//默认编码是iso-8859-1 改为utf-8
restTemplate.getMessageConverters().add(1,new StringHttpMessageConverter(Charset.forName("utf-8")));
return restTemplate;
}
}
编写controller,在controller中直接调用RestTemplate,远程访问userService的服务接口:
@RestController
@RequestMapping("/consumer")
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/{id}")
public User selectById(@PathVariable("id") String id){
return restTemplate.getForObject("http://127.0.0.1:8081/user/" + id,User.class);
}
}
结果:
2.4.问题
通过httpClient技术可以实现两个服务的调用,但是这种方式存在很大的问题
存在什么问题?
- 在consumer中,我们把url地址硬编码到了代码中,不方便后期维护
- consumer需要记忆userService的地址,如果出现变更,可能得不到通知,地址将失效
- consumer不清楚userService的状态,服务宕机也不知道
- userService只有1台服务,不具备高可用性
- 即便userService形成集群,consumer还需自己实现负载均衡
其实上面说的问题,概括一下就是分布式服务必然要面临的问题:
- 服务管理
- 如何自动注册和发现
- 如何实现状态监管
- 如何实现动态路由
- 服务如何实现负载均衡
- 服务如何解决容灾问题
- 服务如何实现统一配置
以上的问题,SpringCloud都给出了解决方案
3.Eureka注册中心
renewal:续约
- Eureka-Server:就是服务注册中心(可以是一个集群),对外暴露自己的地址。
- 提供者:启动后向Eureka注册自己信息(地址,服务名称等),并且定期进行服务续约
- 消费者:服务调用方,会定期去Eureka拉取服务列表,然后使用负载均衡算法选出一个服务进行调用。
- 心跳(续约):提供者定期通过http方式向Eureka刷新自己的状态
3.1.编写EurekaServer
依赖:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
编写启动类:
@SpringBootApplication
@EnableEurekaServer // 声明这个应用是一个EurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
编写配置:
server:
port: 10086
spring:
application:
name: eureka-server # 应用名称,会在Eureka中作为服务的id标识(serviceId)
eureka:
client:
service-url: # EurekaServer的地址,现在是自己的地址,如果是集群,需要写其它Server的地址。
defaultZone: http://127.0.0.1:10086/eureka
register-with-eureka: false # 不注册自己
fetch-registry: false #不拉取服务
启动服务,并访问:http://127.0.0.1:10086
3.2.服务注册
注册服务,就是在服务上添加Eureka的客户端依赖,客户端代码会自动把服务注册到EurekaServer中。
在userService模块中添加Eureka客户端依赖:
<!-- Eureka客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
在启动类上开启Eureka客户端功能
通过添加@EnableDiscoveryClient
来开启Eureka客户端功能
@SpringBootApplication
@MapperScan("com.makeke.mapper")
@EnableDiscoveryClient
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class,args);
}
}
编写配置:
eureka:
client:
service-url: # EurekaServer地址
defaultZone: http://127.0.0.1:10086/eureka
添加spring.application.name属性来指定应用名称,将来会作为服务的id使用。
重启项目访问:http://127.0.0.1:10086
3.3.服务发现
修改调用端代码,用DiscoveryClient类的方法,根据服务名称,获取服务实例:
@RestController
@RequestMapping("/consumer")
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/{id}")
public User selectById(@PathVariable("id") String id){
List<ServiceInstance> userServiceList = discoveryClient.getInstances("userService");
URI uri = userServiceList.get(0).getUri();
return restTemplate.getForObject(uri +"/user/"+ id,User.class);
}
}
3.4.高可用的EurekaServer
多个EurekaServer之间也会互相注册为服务,当服务提供者注册到EurekaServer集群中的某个节点时,该节点会把服务的信息同步给集群中的每个节点,从而实现高可用集群。因此,无论客户端访问到Eureka Server集群中的任意一个节点,都可以获取到完整的服务列表信息
我们假设要搭建两条EurekaServer的集群,端口分别为:10086和10087
1)我们修改原来的EurekaServer配置:
server:
port: 10086 # 端口
spring:
application:
name: eureka-server # 应用名称,会在Eureka中显示
eureka:
client:
service-url: # 配置其他Eureka服务的地址,而不是自己,比如10087
defaultZone: http://127.0.0.1:10087/eureka
2)另外一台配置恰好相反:
server:
port: 10087
spring:
application:
name: eureka-server # 应用名称,会在Eureka中作为服务的id标识(serviceId)
eureka:
client:
service-url: # EurekaServer的地址,现在是自己的地址,如果是集群,需要写其它Server的地址。
defaultZone: http://127.0.0.1:10086/eureka
3)客户端注册服务到集群
因为EurekaServer不止一个,因此注册服务的时候,service-url参数需要变化:
eureka:
client:
service-url: # EurekaServer地址,多个地址以','隔开
defaultZone: http://127.0.0.1:10086/eureka,http://127.0.0.1:10087/eureka
4)启动测试:
- 服务续约:
在注册服务完成以后,服务提供者会维持一个心跳(定时向EurekaServer发起Rest请求),告EurekaServer:“我还活着”。这个称为服务的续约(renewal);
有两个重要参数可以修改服务续约的行为:
eureka:
instance:
lease-renewal-interval-in-seconds: 30
lease-expiration-duration-in-seconds: 90
- lease-renewal-interval-in-seconds:服务续约(renew)的间隔,默认为30秒
- lease-expiration-duration-in-seconds:服务失效时间,默认值90秒
也就是说,默认情况下每个30秒服务会向注册中心发送一次心跳,证明自己还活着。如果超过90秒没有发送心跳,EurekaServer就会认为该服务宕机,会从服务列表中移除。