1.nacos简单部署
2.网关设置
3日志管理.
nacos引用的主要依赖是然后在配置文件进行注册(需要提前启动nacos插件,默认密码都是nacos)
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
在配置文件进行注册 (注册时必须设置服务名)
spring.application.name=shop-product
spring.cloud.nacos.server-addr=localhost:8848
服务直接可以相互调用,调用方式有三种
1.直接输入服务ip(不灵活)
/**
* @program: shop-parent3
* @description:
* @author: 大鱼
* @create: 2021-07-07 19:36
**/
@RestController
public class OrderController {
@Resource
OrderMapper orderMapper;
@Resource
RestTemplate restTemplate;
@GetMapping("insert")
private String insertit(Integer pid, Integer num) {
Order order = new Order();
Product prduct = restTemplate.getForObject("http://localhost:8081/product/byid/"+pid,Product.class);
order.setUsername("xxxx");
orderMapper.insert(order);
return "ok";
}
}
2.从nacos注册中心获取(不符合习惯)
@RestController public class OrderController1 { @Resource OrderMapper orderMapper; @Resource RestTemplate restTemplate; @Resource DiscoveryClient discoveryClient; @GetMapping("insert1") private String insertit(Integer pid, Integer num) { Order order = new Order(); List
instances = discoveryClient.getInstances("shop-product"); ServiceInstance instance = instances.get(0); Product prduct = restTemplate.getForObject(instance.getUri()+"/product/byid/"+pid,Product.class); order.setUsername("xxxx"); orderMapper.insert(order); return "ok"; } }
用DiscoveryClient类获取注册中心的集群,然后获取路径
同时在主启动类加入RestTemplate引用类
@SpringBootApplication
@MapperScan(basePackages = "com.dayu.mapper")
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
3.引用openfeign依赖
org.springframework.cloud
spring-cloud-starter-openfeign
新建一个接口加注解并且指定注册中心想要获取的服务名以及该服务的方法
@FeignClient(value = "shop-product")
@RequestMapping("product")
public interface Myopen {
@GetMapping("byid/{id}")
public Product getit(@PathVariable Integer id);
}
开启注解 @EnableFeignClients生效和 @LoadBalanced(负载均衡)
@SpringBootApplication
@MapperScan(basePackages = "com.dayu.mapper")
@EnableFeignClients
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
在配置文件可声明服务负载均衡的方式
shop-product: # 这里使用服务的名称
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #使用的的负载均衡策略
4.配置文件
微服务的配置文件可以从注册中心进行获取,
1)首先引入依赖
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-config
首先定义一个bootstrap.yml文件
#资源配置文件有优先级pro>yaml>yml
#从nacos 获取资源配置文件
spring:
application:
name: shop-product#微服务名
cloud:
nacos:
config:
server-addr: localhost:8848
file-extension: yaml#文件后缀可变
所谓的API网关,就是指系统的统一入口,它封装了应用程序的内部结构,为客户端提供统一服 务,一些与业务本身功能无关的公共逻辑可以在这里实现,诸如认证、鉴权、监控(黑白名单)、路由转发等等。
首先引入依赖
org.springframework.cloud
spring-cloud-starter-gateway
首先在配置文件注册微服务的相关信息,然后可以在nacos的配置中心进行获取
spring:
cloud:
gateway:
routes:
- id: shop-product
uri: lb://shop-product/ #负载均衡服务名ip
order: 0
predicates:
- Path=/product/** #断言
# - Age=18,60
filters: #过滤器
- SetStatus=250 # - StripPrefix=1
全局过滤器是用来对网关请求所有的服务请求进行过滤的。
@Component
public class AllFilter implements GlobalFilter, Ordered {
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
System.out.println("---------------------------全局拦截器---------------");
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
String token = request.getHeaders().getFirst("token");
System.out.println(token);
if (!StringUtils.isEmpty(token)) {
if ("admin".equals(token)) {
return chain.filter(exchange);//如果请求头含有token并且是admin时对其放性
}
String path = request.getPath().toString();
if (path.contains("/login")) {
return chain.filter(exchange);//判断路径是否包含login(防止空指针异常)
}
}
Map data = new HashMap<>();
DataBuffer buffer = null;
try {
data.put("status", "2222");//将map转成json并且返回前端
data.put("msg", "先登录");
byte[] datas = JSON.toJSONString(data).getBytes("utf-8");//需要阿里的依赖
buffer = response.bufferFactory().wrap(datas);
response.setStatusCode(HttpStatus.UNAUTHORIZED);
response.getHeaders().add("Content-Type","application/json;charset=UTF-8");//编译格式
} catch (Exception e) {
e.printStackTrace();
}
return response.writeWith(Mono.just(buffer));
//
//
// exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
// return exchange.getResponse().setComplete();
}
public int getOrder() {//优先级
return 1;
}
}
转为json的依赖
com.alibaba
fastjson
1.2.72
链路追踪一般采用sleuth和zipkin进行结合首先引入依赖
org.springframework.cloud
spring-cloud-starter-sleuth
org.springframework.cloud
spring-cloud-starter-zipkin
同时启用客户端 并且将数据存储到表中,
java -jar zipkin-server-2.12.9-exec.jar --STORAGE_TYPE=mysql --MYSQL_HOST=localhost --MYSQL_TCP_PORT=3306 --MYSQL_DB=zipkin --MYSQL_USER=root --MYSQL_PASS=123456
建表sql 数据库名zipkin
CREATE TABLE IF NOT EXISTS zipkin_spans (
`trace_id_high` BIGINT NOT NULL DEFAULT 0 COMMENT 'If non zero, this means the trace uses 128 bit traceIds instead of 64 bit',
`trace_id` BIGINT NOT NULL,
`id` BIGINT NOT NULL,
`name` VARCHAR(255) NOT NULL,
`parent_id` BIGINT,
`debug` BIT(1),
`start_ts` BIGINT COMMENT 'Span.timestamp(): epoch micros used for endTs query and to implement TTL',
`duration` BIGINT COMMENT 'Span.duration(): micros used for minDuration and maxDuration query' )
ENGINE=InnoDB ROW_FORMAT=COMPRESSED CHARACTER SET=utf8 COLLATE utf8_general_ci;
ALTER TABLE zipkin_spans ADD UNIQUE KEY(`trace_id_high`, `trace_id`, `id`) COMMENT 'ignore insert on duplicate';
ALTER TABLE zipkin_spans ADD INDEX(`trace_id_high`, `trace_id`, `id`) COMMENT 'for joining with zipkin_annotations';
ALTER TABLE zipkin_spans ADD INDEX(`trace_id_high`, `trace_id`) COMMENT 'for getTracesByIds';
ALTER TABLE zipkin_spans ADD INDEX(`name`) COMMENT 'for getTraces and getSpanNames';
ALTER TABLE zipkin_spans ADD INDEX(`start_ts`) COMMENT 'for getTraces ordering and range';
CREATE TABLE IF NOT EXISTS zipkin_annotations (
`trace_id_high` BIGINT NOT NULL DEFAULT 0 COMMENT 'If non zero, this means the trace uses 128 bit traceIds instead of 64 bit',
`trace_id` BIGINT NOT NULL COMMENT 'coincides with zipkin_spans.trace_id',
`span_id` BIGINT NOT NULL COMMENT 'coincides with zipkin_spans.id',
`a_key` VARCHAR(255) NOT NULL COMMENT 'BinaryAnnotation.key or Annotation.value if type == -1',
`a_value` BLOB COMMENT 'BinaryAnnotation.value(), which must be smaller than 64KB',
`a_type` INT NOT NULL COMMENT 'BinaryAnnotation.type() or -1 if Annotation',
`a_timestamp` BIGINT COMMENT 'Used to implement TTL; Annotation.timestamp or zipkin_spans.timestamp',
`endpoint_ipv4` INT COMMENT 'Null when Binary/Annotation.endpoint is null',
`endpoint_ipv6` BINARY(16) COMMENT 'Null when Binary/Annotation.endpoint is null, or no IPv6 address',
`endpoint_port` SMALLINT COMMENT 'Null when Binary/Annotation.endpoint is null',
`endpoint_service_name` VARCHAR(255) COMMENT 'Null when Binary/Annotation.endpoint is null' )
ENGINE=InnoDB ROW_FORMAT=COMPRESSED CHARACTER SET=utf8 COLLATE utf8_general_ci;
ALTER TABLE zipkin_annotations ADD UNIQUE KEY(`trace_id_high`, `trace_id`, `span_id`, `a_key`, `a_timestamp`) COMMENT 'Ignore insert on duplicate';
ALTER TABLE zipkin_annotations ADD INDEX(`trace_id_high`, `trace_id`, `span_id`) COMMENT 'for joining with zipkin_spans';
ALTER TABLE zipkin_annotations ADD INDEX(`trace_id_high`, `trace_id`) COMMENT 'for getTraces/ByIds';
ALTER TABLE zipkin_annotations ADD INDEX(`endpoint_service_name`) COMMENT 'for getTraces and getServiceNames';
ALTER TABLE zipkin_annotations ADD INDEX(`a_type`) COMMENT 'for getTraces';
ALTER TABLE zipkin_annotations ADD INDEX(`a_key`) COMMENT 'for getTraces';
ALTER TABLE zipkin_annotations ADD INDEX(`trace_id`, `span_id`, `a_key`) COMMENT 'for dependencies job';
CREATE TABLE IF NOT EXISTS zipkin_dependencies (
`day` DATE NOT NULL,
`parent` VARCHAR(255) NOT NULL,
`child` VARCHAR(255) NOT NULL,
`call_count` BIGINT )
ENGINE=InnoDB ROW_FORMAT=COMPRESSED CHARACTER SET=utf8 COLLATE utf8_general_ci;
ALTER TABLE zipkin_dependencies ADD UNIQUE KEY(`day`, `parent`, `child`);
启动端口号时localhost:9411
可以看出链路并且看出服务的时间以及出问题的环节