文章目录
1.Eureka注册与发现
1.1Eureka服务端
Eureka服务端依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
在主配置类上加上@EnableEurekaServer注解
application.yml
server:
port: 1000 #eureka服务端口号
eureka:
instance:
hostname: peer1 #主机名
client:
register-with-eureka: false #禁止向注册中心注册
fetch-registry: false #禁止拉取注册清单地址
service-url: #微服务向注册中心注册的地址
defaultZone: http://peer2:1001/eureka/
#如果Eureka有集群defaultZone写其他服务器的ip地址
1.2Eureka客服端
依赖导入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
主配置类上加上@EnableEurekaClient注解
application.yml
server:
port: 2000
eureka:
client:
service-url:
defaultZone: http://peer1:1000/eureka/,http://peer2:1001/eureka/
# defaultZone对应Eureka服务器集群中所有ip地址
instance:
prefer-ip-address: true
hostname: order-server1
spring:
application:
name: order-server
2.消费者提供者之间通讯
2.1集成ribbon负载均衡器+hystrix熔断器
依赖导入
<!--引入ribbon负载均衡器-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<!--hystrix熔断-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
主配置类上加@EnableHystrix,@RibbonClient可以省略,@Import(Myconfig.class)配置
myconfig配置
@Configuration
public class Myconfig {
@Bean
@LoadBalanced//ribbon的负载均衡器标签,赋予resttemplate负载均衡的功能
public RestTemplate restTemplate(){
return new RestTemplate();
}
//随机策略
@Bean
public IRule rule(){
return new RandomRule();
}
}
消费者访问提供者
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/findone/{id}")
@HystrixCommand(fallbackMethod = "failGet")
public JsonResult findUserById(@PathVariable("id") Long id){
//根据服务集群名选取服务user-server
String url = "http://user-server/user/findone/"+id;
JsonResult jsonResult = restTemplate.getForObject(url, JsonResult.class);
return jsonResult;
}
//熔断后的回调方法
public JsonResult failGet(@PathVariable("id") Long id){
return JsonResult.me().setSuccess(false).setMessage("该服务已降级");
}
}
2.2Feign负载均衡器+hystrix熔断器
依赖导入
<!--引入feign负载均衡器-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--hystrix熔断-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
主配置类上加@EnableFeignClients("com.wal.springcloud.client")
application.yml
feign:
hystrix:
enabled: true #开启熔断支持
client:
config:
remote-service: #服务名,填写default为所有服务
connectTimeout: 3000
readTimeout: 3000
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000
消费者访问提供者
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private UserFeignClient userFeignClient;
@GetMapping("/findone/{id}")
public JsonResult findUserById(@PathVariable("id") Long id){
JsonResult jsonResult = userFeignClient.findUserById(id);
return jsonResult;
}
}
Feign客户端
@FeignClient(value = "user-server",
configuration = UserFeignConfiguration.class,
fallback = UserFeignClientFallBack.class)
public interface UserFeignClient {
@GetMapping("/user/findone/{id}")
public JsonResult findUserById(@PathVariable("id") Long id);
}
熔断后的回调方法
@Component
public class UserFeignClientFallBack implements UserFeignClient {
//返回托底数据
@Override
public JsonResult findUserById(Long id) {
return JsonResult.me().setSuccess(false)
.setMessage("服务当前不可用")
.setData(new User(id,"123","1233"));
}
}
feign配置
@Configuration
public class UserFeignConfiguration {
@Bean
public IRule rule(){
return new RandomRule();
}
}
2.3熔断
如果调用持续出错或者超时,电路被打开进入熔断状态(Open),后续一段时间内的所有调用都会被拒绝(Fail Fast),
一段时间以后,保护器会尝试进入半熔断状态(Half-Open),允许少量请求进来尝试,
如果调用仍然失败,则回到熔断状态
如果调用成功,则回到电路闭合状态;
2.3.2熔断隔离模式
1.线程池隔离模式:使用一个线程池来储存请求,优点可以应对突发流量,缺点资源消耗大。
2.信号量隔离模式:用一个计数器来统计当前有多少个线程,
若超过最大线程数,则拒绝新请求
3.zuul网关
网关有鉴权,限流,请求分发等作用,网关服务也需要向注册中心注册
依赖导入
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<!--alibaba json转换插件-->
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.57</version>
</dependency>
</dependencies>
主配置类上添加@EnableZuulProxy和@EnableEurekaClient注解
网关中已经集成ribbon和hystrix
配置文件application.yml
server:
port: 4000
eureka:
instance:
hostname: springcloud-zuul
prefer-ip-address: true
client:
service-url:
defaultZone: http://peer1:1000/eureka/,http://peer2:1001/eureka/
spring:
application:
name: springcloud-zuul
zuul:
routes:
order-server: "/order/**" #服务名映射,使用/order\/**路径访问服务
user-server: "/user/**"
ignored-services: "*" #所有服务都不能用服务名来访问
retryable: true #
ribbon:
ConnectTimeout: 2500 # 连接超时时间(ms)
ReadTimeout: 2000 # 通信超时时间(ms)
OkToRetryOnAllOperations: true # 是否对所有操作重试
MaxAutoRetriesNextServer: 2 # 同一服务不同实例的重试次数
MaxAutoRetries: 1 # 同一实例的重试次数
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMillisecond: 3000 # 熔断超时时长:3000ms
自定义网关过滤器
@Component
public class MyZuulFilter extends ZuulFilter {
//过滤器类型,前置过滤器,后置过滤器,
@Override
public String filterType() {
return FilterConstants.PRE_TYPE;
}
//过滤器执行顺序,值越小优先级越高
@Override
public int filterOrder() {
return FilterConstants.PRE_DECORATION_FILTER_ORDER;
}
//返回true为过滤器有效会执行run方法,返回false直接交给下一个过滤器
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
// 1)获取Zuul提供的请求上下文对象
RequestContext currentContext = RequestContext.getCurrentContext();
//获得请求对象
HttpServletRequest request = currentContext.getRequest();
String uri = request.getRequestURI();
//如果uri中包含11则直接放行
if (!uri.contains("11")){
HttpServletResponse response = currentContext.getResponse();
response.setContentType("text/json;charset=utf-8");
HashMap<String, Object> map = new HashMap<>();
map.put("success", false);
map.put("message", "id错误");
String string = JSON.toJSONString(map);
//拦截
currentContext.setSendZuulResponse(false);
//返回状态码
currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
try {
response.getWriter().write(string);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
网关跨域配置
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
//1.添加CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//1) 允许的域,不要写*,否则cookie就无法使用了
config.addAllowedOrigin("http://127.0.0.1:6001");
config.addAllowedOrigin("http://localhost:6001");
//2) 是否发送Cookie信息
config.setAllowCredentials(true);
//3) 允许的请求方式
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
// 4)允许的头信息
config.addAllowedHeader("*");
//2.添加映射路径,我们拦截一切请求
UrlBasedCorsConfigurationSource configSource = new
UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
//3.返回新的CorsFilter.
return new CorsFilter(configSource);
}
}
4.springcloudconfig,配置文件集中管理
依赖导入springcloud客服端,也需要向注册中心注册
<!--eureka客户端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--配置中心支持-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
在主配置类上添加@EnableEurekaClient和@EnableConfigServer注解
application.yml
server:
port: 5000
eureka:
client:
service-url:
defaultZone: http://peer1:1000/eureka/,http://peer2:1001/eureka/
instance:
prefer-ip-address: true
hostname: springcloud-config
spring:
application:
name: springcloud-config
cloud:
config:
server:
git:
uri: https://github.com/jvjvangwu/jvjvangwu.git #远程仓库地址
username: *****
password: *****
springcloud客户端
依赖导入
<!--configclient端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
将配置文件名设置为bootstrap.yml
spring:
cloud:
config:
name: application-order #github上的名字
profile: test #环境
label: master #分支
uri: http://localhost:5000 #config服务器地址