从天气项目看 Spring Cloud 微服务治理| |API网关进行统一

API网关:主要统一API入口
如:天气数据API、城市数据API,当需要调用这些API时,是直接通过名称来调用,在管理上没有统一的管理,直接由应用来调用

API网管的意义

集合多个API:直接调用网关,网关进行转发相应的微服务
统一的API入口:
在这里插入图片描述
应用不知道具体的微服务的功能,通过网关调用

API网关带来的好处

1、避免将内部信息泄露给外部
2、为微服务添加额外的安全层:防止SQL注入
3、支持混合通信协议:Http协议、消息中间件
4、降低构建微服务的复杂性
5、微服务模拟与虚拟化

API网关的弊端

1、在架构上需要额外考虑更多编排与管理
2、路由逻辑配置要进行统一的管理
3、可能引发单点故障:有很多访问这个微服务实例

常见的API网关的实现方式

Nginx(用的多,以后工作要用)

在这里插入图片描述
配置简单

Spring Cloud Zuul

在这里插入图片描述

Kong提供微服务

在这里插入图片描述

如何集成Zuul

功能:在这里插入图片描述
在这里插入图片描述
eureka-weather-eureka-client-zuul
添加依赖:

// Zuul
	compile('org.springframework.cloud:spring-cloud-starter-netflix-zuul')

修改启动类注解:

@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

修改配置文件
在这里插入图片描述
启动micro-weather-eureka-server
启动micro-weather-eureka-client-zuul

实现API网关

在这里插入图片描述
在这里插入图片描述
msa-weather-eureka-client-zuul-gateway
引入依赖:

// Zuul
	compile('org.springframework.cloud:spring-cloud-starter-netflix-zuul')

修改启动类注解:

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

修改配置文件
在这里插入图片描述
为网关提供创建一个接口、数据统一的接口

@FeignClient("msa-weather-eureka-client-zuul")
public interface DataClient {
	/**
	 * 获取城市列表
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/city/cities")
	List<City> listCity() throws Exception;
	
	/**
	 * 根据城市ID查询天气数据
	 */
	@GetMapping("/data/weather/cityId/{cityId}")
	WeatherResponse getDataByCityId(@PathVariable("cityId") String cityId);
}

@Service
public class WeatherReportServiceImpl implements WeatherReportService {
	@Autowired
	private DataClient dataClient;
	@Override
	public Weather getDataByCityId(String cityId) {
		// 由天气数据API微服务来提供
		WeatherResponse resp = dataClient.getDataByCityId(cityId);
		Weather data = resp.getData();
		return data;
	}
}

启动msa-weather-collection-eureka-feign 启动在端口8081
启动msa-weather-collection-eureka-feign 启动在端口8082
启动msa-weather-data-eureka 启动在端口8083
启动msa-weather-data-eureka 启动在端口8084
启动msa-weather-city-eureka 启动在端口8085
启动msa-weather-city-eureka 启动在端口8086
启动msa-weather-report-eureka-feign-gateway 启动在端口8087
启动msa-weather-report-eureka-feign-gateway 启动在端口8088
启动msa-weather-report-eureka-client-zuul 启动在端口8088

在这里插入图片描述
访问:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值