-
ktry-parent
· pom.xml
<!-- springboot 整合web组件--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <version>0.2.2.RELEASE</version> </dependency>
-
ktry-book
·service.BookService.java
@RestController public class BookService { @Value("${server.port}") private String serverPort; /** * 会员服务提供的接口被订单服务调用 */ @GetMapping("/getBook") public String getBook(Integer userId) { return "Book,端口号为:" + serverPort; } }
·application.yml
spring: application: ###服务的名称 name: ktry-book cloud: nacos: discovery: ###nacos注册地址 server-addr: 127.0.0.1:8848 server: port: 8070
-
ktry-oeder
·AppOrder.java
@SpringBootApplication public class AppOrder { public static void main(String[] args) { SpringApplication.run(AppOrder.class); } /** * 加上LoadBalanced 注解就可以实现我们的本地负载均衡 */ @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } }
·application.yml
spring: application: ###服务的名称 name: ktry-oeder cloud: nacos: discovery: ###nacos注册地址 server-addr: 127.0.0.1:8848 server: port: 8080
·service.BookService.java
@RestController public class BookService { @Autowired private RestTemplate restTemplate; /** * 基于Ribbon实现本地负载均衡 */ @RequestMapping("/orderToRibbonBook") public Object orderToRibbonMember() { String result = restTemplate.getForObject("http://meitemayikt-book/getBook", String.class); return "订单调用会员返回结果:" + result; } }
-
ktry-gateway
·application.yml
server: port: 80 ####服务网关名称 spring: application: name: ktry-gateway cloud: gateway: ###路由策略 routes: ###根据我们的服务名称查找地址实现调用 - id: book ####转发http://www.mayikt.com/ uri: lb://meitemayikt-book/ filters: - StripPrefix=1 ###匹配规则 predicates: - Path=/book/** - id: mayikt uri: http://www.mayikt.com/ predicates: - Path=/mykt/** discovery: locator: ###允许通过注册中心获取地址调用 enabled: true nacos: discovery: server-addr: 127.0.0.1:8848
·filter.TokenGlobalFilter.java
//拦截器 @Component public class TokenGlobalFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { String token = exchange.getRequest().getQueryParams().getFirst("token"); if (StringUtils.isEmpty(token)) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR); String msg = "token not is null "; DataBuffer buffer = response.bufferFactory().wrap(msg.getBytes()); return response.writeWith(Mono.just(buffer)); } // 直接转发到我们真实服务 return chain.filter(exchange); } @Override public int getOrder() { return 0; } }
·动态添加路由servive.GatewayService.java
@Service public class GatewayService implements ApplicationEventPublisherAware { private ApplicationEventPublisher publisher; @Autowired private RouteDefinitionWriter routeDefinitionWriter; @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.publisher = applicationEventPublisher; } public String loadRoute(GateWayEntity gateWayEntity) { RouteDefinition definition = new RouteDefinition(); Map<String, String> predicateParams = new HashMap<>(8); PredicateDefinition predicate = new PredicateDefinition(); FilterDefinition filterDefinition = new FilterDefinition(); Map<String, String> filterParams = new HashMap<>(8); URI uri = null; if ("0".equals(gateWayEntity.getRouteType())) { // 如果配置路由type为0的话 则从注册中心获取服务地址 uri = UriComponentsBuilder.fromUriString("lb://" + gateWayEntity.getRouteUrl() + "/").build().toUri(); } else { uri = UriComponentsBuilder.fromHttpUrl(gateWayEntity.getRouteUrl()).build().toUri(); } // 定义的路由唯一的id definition.setId(gateWayEntity.getRouteId()); predicate.setName("Path"); //路由转发地址 predicateParams.put("pattern", gateWayEntity.getRoutePattern()); predicate.setArgs(predicateParams); // 名称是固定的, 路径去前缀 filterDefinition.setName("StripPrefix"); filterParams.put("_genkey_0", "1"); filterDefinition.setArgs(filterParams); definition.setPredicates(Arrays.asList(predicate)); definition.setFilters(Arrays.asList(filterDefinition)); definition.setUri(uri); routeDefinitionWriter.save(Mono.just(definition)).subscribe(); this.publisher.publishEvent(new RefreshRoutesEvent(this)); return "success"; } }
·pojo.GateWayEntity.java
@Data @AllArgsConstructor public class GateWayEntity { private Long id; private String routeId; private String routeName; private String routePattern; private String routeType; private String routeUrl; }
·测试
@RestController public class GatewayController { @Autowired private GatewayService gatewayService; /** * 同步网关配置 * * @return */ @RequestMapping("/synGatewayConfig") public String synGatewayConfig() { GateWayEntity gateWayEntity = new GateWayEntity(null,"book","meitemayiktbook","/book/**","0","meitemayikt-book"); return gatewayService.loadRoute(gateWayEntity); } }
·解决全局跨域filter.CrossOriginFilter.java
@Component public class CrossOriginFilter implements GlobalFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); ServerHttpResponse response = exchange.getResponse(); HttpHeaders headers = response.getHeaders(); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, PUT, OPTIONS, DELETE, PATCH"); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*"); headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*"); return chain.filter(exchange); } }
<!-- 分布式配置中心 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>0.2.2.RELEASE</version>
</dependency>
application.yml -> bootstrap
config:
server-addr:
file-extension: yaml
@RefreshScope 刷新
seata表
CREATE TABLE `branch_table` (
`branch_id` bigint(20) NOT NULL,
`xid` varchar(128) NOT NULL,
`transaction_id` bigint(20) DEFAULT NULL,
`resource_group_id` varchar(32) DEFAULT NULL,
`resource_id` varchar(256) DEFAULT NULL,
`lock_key` varchar(128) DEFAULT NULL,
`branch_type` varchar(8) DEFAULT NULL,
`status` tinyint(4) DEFAULT NULL,
`client_id` varchar(64) DEFAULT NULL,
`application_data` varchar(2000) DEFAULT NULL,
`gmt_create` datetime DEFAULT NULL,
`gmt_modified` datetime DEFAULT NULL,
PRIMARY KEY (`branch_id`),
KEY `idx_xid` (`xid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `global_table` (
`xid` varchar(128) NOT NULL,
`transaction_id` bigint(20) DEFAULT NULL,
`status` tinyint(4) NOT NULL,
`application_id` varchar(32) DEFAULT NULL,
`transaction_service_group` varchar(32) DEFAULT NULL,
`transaction_name` varchar(128) DEFAULT NULL,
`timeout` int(11) DEFAULT NULL,
`begin_time` bigint(20) DEFAULT NULL,
`application_data` varchar(2000) DEFAULT NULL,
`gmt_create` datetime DEFAULT NULL,
`gmt_modified` datetime DEFAULT NULL,
PRIMARY KEY (`xid`),
KEY `idx_gmt_modified_status` (`gmt_modified`,`status`),
KEY `idx_transaction_id` (`transaction_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `lock_table` (
`row_key` varchar(250) NOT NULL,
`xid` varchar(96) DEFAULT NULL,
`transaction_id` mediumtext,
`branch_id` mediumtext,
`resource_id` varchar(256) DEFAULT NULL,
`table_name` varchar(100) DEFAULT NULL,
`pk` varchar(36) DEFAULT NULL,
`gmt_create` datetime DEFAULT NULL,
`gmt_modified` datetime DEFAULT NULL,
PRIMARY KEY (`row_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
网友评论