来源:
https://blog.csdn.net/qq_35275233/article/details/89041647
概要:基于netflix的springcloud搭建微信点餐系统
目录
第一部分 项目概要
1、项目环境信息
2、介绍
第二部分 搭建Eureka Server
1、配置Eureka 的application.yml
2、配置Eureka pom.xml
3、Eureka 入口类
4、Eureka的高可用
第三部分 客户端注册发现
1、客户端入口类
2、Client新建application.yml
3、Client新建pom.xml
4、客户端书写中间实体(*)
5、商品的更新字段的处理
第四部分 Ribbon实现负载均衡,对比RestTemplate和Feign的使用
1、了解ribbon
2、ribbon的工作原理
3、RestTemplate 操作和Feign简单对比
第五部分 config配置中心
1、Config服务引入pom.xml
2、Config服务配置yml文件
3、Config启动类上引入ConfigServer注解
基于netflix eureka做了二次封装
两个组件组成:
- Eureka Server 注册中心
- Eureka Client 服务注册
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
register-with-eureka: false #默认为true,是否向自己注册自己
server:
enable-self-preservation: false #显示客户端连接状态
spring:
application:
name: spring-cloud-eureka
server:
port: 8761
-- 由于廖师兄的版本采用默认的,无法完成注册
springboot 版本采用 1.5.10.RELEASE
SpringCloud版本采用Edgware.SR2
<?xml version="1.0" encoding="UTF-8"?>
<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.smileLsf</groupId>
<artifactId>eureka</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>eureka</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</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>Edgware.SR2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
<version>1.4.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
-- 添加EnableEurekaServer注解
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
设置启动端口在VM options设置启动端口
-Dserver.port=8761
启动多个可以如下配置,相互注册,截取廖师兄的图一用
-- 添加EnableDiscoveryClient,提供eureka客户端
@EnableDiscoveryClient
@SpringBootApplication
public class ProductApplication {
public static void main(String[] args) {
SpringApplication.run(ProductApplication.class, args);
}
}
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
# instance:
# hostname: product #页面跳转后台端口前名称
spring:
application:
name: product
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/springcloud_sell?characterEncoding=utf-8&useSSL=false
jpa:
show-sql: true
env:
dev
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</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>Edgware.SR2</spring-cloud.version>
<product-common.version>0.0.1-SNAPSHOT</product-common.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>
<dependency>
<groupId>com.smilelsf</groupId>
<artifactId>product-common</artifactId>
<version>${product-common.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
@Data
public class ProductVO {
/**
* 此处需要返回给前端name,但是表示的是类目名称,所以添加JsonProperty进行标识
*/
@JsonProperty("name")
private String categoryName;
@JsonProperty("type")
private Integer categoryType;
@JsonProperty("foods")
List<ProductInfoVO> productInfoVOList;
}
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间 -- 修改时自动更新',
@Data
@Entity
@DynamicUpdate
public class ProductInfo {}
商品实体添加@DynamicUpdate注解
Eureka属于客户端发现,客户端会向服务器拉取可用的服务器信息,根据负载均衡服务,命中那台服务器发送请求,整个过程都是在客户端完成,并不需要服务器的参与。
Ribbon是netflix ribbon实现的,通过springcloud的封装,轻松的面向服务的rest的模板请求,自动的转换为客户端服务调用。
RestTemplate/zuul/Feign都使用到了ribbon
SpringCloud在结合ribbon的负载均衡实践中,封装增加了HTTPClient和OKHttpClient 两种请求端实现,默认使用了ribbon对eureka的客户端发现的负载均衡client
轮寻RoundRobinRule、随机连接RandomRule
ribbon实现软负载均衡核心有三点
(1)服务发现:依据实例名称,把该实例下所有的实例都找出来
(2)服务选择规则:依据规则从多个规则中选择有效的服务
(3)服务监听:检测失效的服务,做到高效剔除
ribbon主要组件
serverList (获取所有的可用服务列表)----> ServerListFilter(过滤掉一部分地址) -----> IRule从剩下的地址中选择一个实例,作为目标结果
a、RestTemplate 操作
详解restTemplate操作 https://blog.csdn.net/itguangit/article/details/78825505
方式一:直接使用restTemplate,路径固定了不好修改
restTemplate对于路径的访问比较固定,如果线上部署,不好进行修改;或者是启动了多个实例,不好进行捕获和调用
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://localhost:9001/msg", String.class);
log.info("response{}",response);
return response;
方式二:利用LoadBalancerClient通过应用名获取url,然后在使用restTemplate
注入LoaderBalancerClient,通过服务名称进行获取服务的ip和端口号
@Autowired
private LoadBalancerClient loadBalancerClient;
@GetMapping("/getProductMsg")
public String getProductMsg(){
// 方式二:(利用LoadBalancerClient通过应用名获取url,然后在使用restTemplate)
RestTemplate restTemplate = new RestTemplate();
ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
String url = String.format("http://%s:%s", serviceInstance.getHost(),serviceInstance.getPort() + "/msg");
String response = restTemplate.getForObject(url, String.class);
log.info("response{}",response);
return response;
}
方式三:通过LoadBalanced实例化restTemplate
@Component
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
通过模块名称进行访问,随机分配一个服务
String response = restTemplate.getForObject("http://PRODUCT/msg", String.class);
b、Feign进行通信
声明式Rest客户端(伪RPC)采用了基于接口的注解第一步:引入pom.xml依赖
<!--应用间通信-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
第二步:添加EnableFeignClient注解
第三步:通过@FeignClient声明被调用的服务信息
@FeignClient(value = "product", fallback = ProductClientFallbackImpl.class )
public interface ProductClient {
/**
* 获取产品端的信息
*
* @return
*/
@GetMapping("/msg")
String getProductMsg();
}
通过fallback处理异常等信息
@Component
@Slf4j
public class ProductClientFallbackImpl implements ProductClient {
/**
* 获取产品端的信息
*
* @return
*/
@Override
public String getProductMsg() {
log.info("返回消息接口出现问题");
return null;
}
}
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
spring:
application:
name: config
cloud:
config:
server:
git:
uri: https://gitee.com/SmileLsf/springCloud_configRepo
username: 用户名
password: 密码
basedir: /IDEAWorkSpace/springcloud_sell_v2/config/basedir
@SpringBootApplication
@EnableEurekaClient
@EnableConfigServer
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
<!--config配置中心-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
bootstrap.yml中配置
spring:
application:
name: order
cloud:
config:
discovery:
enabled: true
service-id: CONFIG #配置中心的服务名称
profile: dev
配置完成之后通过
localhost:8989/order-dev.yml进行访问
通过localhost:8989/bus/refresh 进行动态刷新本地的配置信息
配置中心出现的问题:
a、springcloud 消息总线读取配置文件的两种方式
https://blog.csdn.net/qq_35275233/article/details/89074886
b、springcloud监控配置中心健康状态
https://blog.csdn.net/qq_35275233/article/details/89074380
c、SpringCloud 配置中心执行bus/refresh 出现 Full authentication is required to access this resource
https://blog.csdn.net/qq_35275233/article/details/89074294
/**
* 测试给家电和水果服务发送消息
*/
@Test
public void sendOrderMqMsg() {
amqpTemplate.convertAndSend("myOrder","computer","now:" + new Date());
}
/**
* 1/测试给家电服务发送消息
* @param message
*/
@RabbitListener(bindings = @QueueBinding(
exchange = @Exchange("myOrder"),
key = "computer",
value = @Queue("computerOrder")
))
public void processComputer (String message) {
log.info("ComputerOrder:{}",message);
}
/**
* 2/测试给水果服务发送消息
* @param message
*/
@RabbitListener(bindings = @QueueBinding(
exchange = @Exchange("myOrder"),
key = "fruit",
value = @Queue("fruitOrder")
))
public void processFruit (String message) {
log.info("FruitOrder:{}",message);
}
官方定义stream为微服务应用构建消息驱动能力的框架,为springcloud的另一个组件
目前springcloud支持的消息中间件是RabbitMQ和Kafka
1、引入pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
2、待补充
路由 + 过滤器 = zuul
除了springbus外,zuul也可以实现自动刷新配置/**
* 实现配置的动态注入
*/
@Component
public class ZuulConfig {
@ConfigurationProperties("zuul")
@RefreshScope
public ZuulProperties zuulProperties() {
return new ZuulProperties();
}
}
1、访问前进行参数校验
pre-filter:请求到目标结果之前,对返回的结果进行加工,访问连接中需要添加token,进行接口加密校验@Component
public class TokenFilter extends ZuulFilter {
@Override
public String filterType() {
return PRE_TYPE;
}
@Override
public int filterOrder() {
return PRE_DECORATION_FILTER_ORDER - 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
RequestContext requestContext = RequestContext.getCurrentContext();
HttpServletRequest request = requestContext.getRequest();
String token = request.getParameter("token");
if (StringUtils.isEmpty(token)) {
requestContext.setSendZuulResponse(false);
requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
}
return null;
}
}
2、post-fileter : 请求到目标结果之后,对返回的结果进行加工
@Component
public class AddResponseHeaderFilter extends ZuulFilter {
@Override
public String filterType() {
return POST_TYPE;
}
@Override
public int filterOrder() {
return SEND_RESPONSE_FILTER_ORDER - 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
/**
* 往返回的结果添加x-foo
*/
RequestContext requestContext = RequestContext.getCurrentContext();
HttpServletResponse response = requestContext.getResponse();
response.setHeader("X-FOO", UUID.randomUUID().toString());
return null;
}
}
时机:请求被转发之前调用
令牌桶:拿到令牌的放行
限流过滤器
/**
* 限流过滤器
*/
@Component
public class RateLimitFilter extends ZuulFilter {
/**
* guava的令牌桶算法:放入100个令牌
*/
private static final RateLimiter RATE_LIMITER = RateLimiter.create(100);
@Override
public String filterType() {
return PRE_TYPE;
}
@Override
public int filterOrder() {
return SERVLET_DETECTION_FILTER_ORDER - 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
/**
* tryAcquire(1, 0, TimeUnit.MICROSECONDS);
* 取到一个令牌
*/
if (!RATE_LIMITER.tryAcquire()) {
throw new RateLimitException();
}
return null;
}
}