业务系统子网路由表结构设计及代码实现

1.背景

系统中需要增加子网及路由管理功能,公有云平台设计的subnet、routetable、route之间的关系是routetable可以有多个route,routetable可以对应多个subnet,我侧系统只需要展示subent和route的关系

2.实现

我侧系统只需要展示subnet和route的关系,考虑后续可能扩展功能,表结构还是按照实际对象关系进行设计,页面展示只展示subnet和route。由于底层提供的接口只有同步subnet的接口,没有routetable对应的接口,所以通过subnet list的接口获取到routetable set集合,然后比对db中的routetable集合进行增删routetable,subnet entity的routetable级联属性需要去除掉;同理subnet也进行和db中的subnet进行比对进行增删。先进行routetable的入库,后进行subnet的入库,并且去除事务。

entity

route

public class Route implements Serializable {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@EqualsAndHashCode.Exclude
	private Long id;

	@ManyToOne
	@JsonIgnore
	@ToString.Exclude
	@EqualsAndHashCode.Exclude
	@JoinColumn(name = "route_table_id")
	private RouteTable routeTable;

	//目的地 172.16.0.0/16
	private String destinationCidr;

	//目标 172.16.0.1
	private String gatewayId;

	private Boolean deleted = false;
}

routetable

public class RouteTable implements Serializable {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;

	private String csRouteTableId;

	private Boolean deleted = false;

	@ToString.Exclude
	@EqualsAndHashCode.Exclude
	@OneToMany(mappedBy = "routeTable", cascade = CascadeType.ALL)
	private List<Subnet> subnets;

	@ToString.Exclude
	@EqualsAndHashCode.Exclude
	@OneToMany(mappedBy = "routeTable", cascade = CascadeType.ALL)
	private List<Route> routes;
}

subnet

public class Subnet extends BaseDomain {

	private String csSubnetId;

	//可用区id
	private String zoneId;

	private String username;

	@ManyToOne(fetch = FetchType.LAZY)
	@JsonIgnore
	@ToString.Exclude
	@EqualsAndHashCode.Exclude
	@JoinColumn(name = "route_table_id")   //去除级联操作 cascade = CascadeType.ALL
	private RouteTable routeTable;
}

sync subnet和routetable

public void syncSubnet() {
		log.info("start syncSubnet");
		List<Subnet> subnets = subnetGrpcService.getSubnets();

		//todo: add sync routeTable
		Set<RouteTable> routeTables = subnets.stream().map(Subnet::getRouteTable).collect(Collectors.toSet());
		List<RouteTable> routeTableList = routeTables.stream().map(routeTable -> addOrUpdateRouteTable(routeTable)).toList();
		if (!CollectionUtils.isEmpty(routeTableList)) {
			routeTableRepository.saveAll(routeTableList);
		}

		//subnet
		List<Subnet> subnetDbs = subnetRepository.findAll();
		List<Subnet> subnetList = Optional.ofNullable(subnets)
				.stream().parallel().flatMap(Collection::parallelStream)
				.map(csSubnet -> addOrUpdateSubnet(csSubnet, subnetDbs)).toList();
		if (!CollectionUtils.isEmpty(subnetList)) {
			Optional.ofNullable(subnetDbs).filter(Predicate.not(CollectionUtils::isEmpty)).ifPresent(s -> {
				subnetList.addAll(subnetDbs.stream().map(m -> {
					m.setDeleted(true);
					return m;
				}).toList());
			});
			subnetRepository.saveAll(subnetList);
		}
		log.info("end syncSubnet");
	}
posted @ 2022-01-15 17:16  你若安好便是晴天1208  阅读(99)  评论(0编辑  收藏  举报