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
访问: