Share
Embed
Alfa Microservices, Spring Boot and Spring Cloud
About architecture, spring boot and spring cloud ecosystem
Kirill Tolkachev
April 28, 2019
Transcript
557 slides
-
CORBA. Плюсы • Независимость от конкретного языка или технологии (не
считая ORB) • Простое соблюдение контракта -
CORBA. Минусы • Смешение локальных и распределенных географически взаимодействий ведет
к непредсказуемым проблемам с производительностью -
CORBA. Минусы • Смешение локальных и распределенных географически взаимодействий ведет
к непредсказуемым проблемам с производительностью • Сложная раздутая спецификация с проблемами версий от разных вендоров -
CORBA. Минусы • Смешение локальных и распределенных географически взаимодействий ведет
к непредсказуемым проблемам с производительностью • Сложная раздутая спецификация с проблемами версий от разных вендоров • Специфические протоколы поверх tcp/ip, порты которых часто попадали под блокировки -
CORBA. Минусы • Смешение локальных и распределенных географически взаимодействий ведет
к непредсказуемым проблемам с производительностью • Сложная раздутая спецификация с проблемами версий от разных вендоров • Специфические протоколы поверх tcp/ip, порты которых часто попадали под блокировки -
Проблема надежности канал связи • Отказ от кастомных протоколов и
переход на HTTP • Переход на платформонезависимые языки спецификации сообщений (json, xml) -
Проблема локальности обращений • Отказ от слоя абстракции скрывающего процесс
получения данных - удаленные вызовы стали явными, разработчики стали следить за количеством удаленных вызовов -
Проблема сложной спецификации • CORBA умер, SOAP учел его ошибки
• ...но не до конца, REST был проще и почти закопал SOAP • ...продолжение следует -
SOA. Плюсы • Независимость набора технологий, развёртывания и масштабируемости сервисов.
• Удобство параллелизации разработки -
SOA. Плюсы • Независимость набора технологий, развёртывания и масштабируемости сервисов.
• Удобство параллелизации разработки • Стандартный, простой и надёжный канал связи (передача текста по HTTP через порт 80). • Оптимизированный обмен сообщениями -
SOA. Плюсы • Независимость набора технологий, развёртывания и масштабируемости сервисов.
• Удобство параллелизации разработки • Стандартный, простой и надёжный канал связи (передача текста по HTTP через порт 80). • Оптимизированный обмен сообщениями • Стабильная спецификация обмена сообщениями. • Изолированность контекстов доменов (Domain contexts). -
Шина. Плюсы • Независимость технологий, развёртывания и масштабирования • Стандартный,
простой и надёжный канал связи • Оптимизированный обмен сообщениями. • Стабильная спецификация обмена сообщениями. -
Шина. Плюсы • Независимость технологий, развёртывания и масштабирования • Стандартный,
простой и надёжный канал связи • Оптимизированный обмен сообщениями. • Стабильная спецификация обмена сообщениями. • Асинхронность обмена сообщениями и управление нагрузкой на систему. -
Шина. Плюсы • Независимость технологий, развёртывания и масштабирования • Стандартный,
простой и надёжный канал связи • Оптимизированный обмен сообщениями. • Стабильная спецификация обмена сообщениями. • Асинхронность обмена сообщениями и управление нагрузкой на систему. • Единая точка для управления версионированием и преобразованием форматов -
Шина. Минусы • Ниже скорость связи, особенно между уже совместимыми
сервисами. • Единая точка отказа, способная обрушить системы связи всей компании. -
Шина. Минусы • Ниже скорость связи, особенно между уже совместимыми
сервисами. • Единая точка отказа, способная обрушить системы связи всей компании. • Большая сложность конфигурирования и поддержки. • Шина так сложна, что для её управления вам потребуется целая команда. -
Попробуем отгадать • Простота масштабирования • Удобство параллельной разработки несколькими
командами • Переиспользование в разных продуктах • ??? -
DaDD. Плюсы • Немного проще писать тесты • Меньше шансов
создать сильную связку между классами сущностей • Меньше кода -
DaDD. Минусы • На большом количестве сущностей проще скатиться в
написание монстр- логики • Уход от ООП (?) -
Какие проблемы надо решать в микросервисах? • Свобода выбора стека
или простота поддержки? -
Какие проблемы надо решать в микросервисах? • Свобода выбора стека
или простота поддержки? • Как не сожрать все ресурсы? • Как собирать логи и как мониторить? -
Какие проблемы надо решать в микросервисах? • Свобода выбора стека
или простота поддержки? • Как не сожрать все ресурсы? • Как собирать логи и как мониторить? • Как обновлять api и не сломать совместимость? • Как обновлять без даунтайма? -
Какие проблемы надо решать в микросервисах? • Свобода выбора стека
или простота поддержки? • Как не сожрать все ресурсы? • Как собирать логи и как мониторить? • Как обновлять api и не сломать совместимость? • Как обновлять без даунтайма? • Как масштабировать и балансировать нагрузку? • Как отслеживать и останавливать распространение ошибок? -
Какие проблемы надо решать в микросервисах? • Свобода выбора стека
или простота поддержки? • Как не сожрать все ресурсы? • Как собирать логи и как мониторить? • Как обновлять api и не сломать совместимость? • Как обновлять без даунтайма? • Как масштабировать и балансировать нагрузку? • Как отслеживать и останавливать распространение ошибок? • Как не закопать бизнес-логику среди инфраструктурных классов? • Как обновлять общие механизмы? -
Какие проблемы надо решать в микросервисах? • Свобода выбора стека
или простота поддержки? • Как не сожрать все ресурсы? • Как собирать логи и как мониторить? • Как обновлять api и не сломать совместимость? • Как обновлять без даунтайма? • Как масштабировать и балансировать нагрузку? • Как отслеживать и останавливать распространение ошибок? • Как не закопать бизнес-логику среди инфраструктурных классов? • Как обновлять общие механизмы? • Как не угробить расплывающуюся архитектуру? • Как ... -
На чем можно клепать микросервисы java-dev? • Spring Boot •
Ratpack • Micronaut • Spark • spring-fu • etc. -
Что у нас на сегодня? • Spring...Boot, как он работает
и как использовать его на полную • Начнем смотреть Spring cloud из чего состоит какой он был и как изменился -
All your classes All your pages and xmls Regular web.xml
with spring dispatcher servlet, spring listener and security filter name Security filters, users and roles Spring MVC beans Application beans, Import security.xml The project structure -
web.xml <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> -
… <context-param> <param-name>contextClass</ param-name> <param-value>…AnnotationConfigWebApplicationContext</ param-value> </context-param> <context-param> <param-name>contextConfigLocation</ param-name>
<param-value>com.inwhite.conf.AppConfig</ param-value> </context-param> … -
Deployment →Use maven/gradle to build a war from that project
→Copy it to webapps directory of tomcat -
How does it work? User type in his browser: http://localhost:8080/myApp
create Spring ContextLoaderListener Start tomcat start applicationContext In bootsrap In bootsrap Create filter mapping Create security filter login Create spring dispatcher servlet Delegate to Controller -
§ 8.2.4 Shared libraries / runtimes pluggability The ServletContainerInitializer class
is looked up via the jar services API. For each application, an instance of the ServletContainerInitializer is created by the container at application startup time. The framework providing an implementation of the ServletContainerInitializer MUST bundle in the META-INF/services directory of the jar file a file called javax.servlet.ServletContainerInitializer, as per the jar services API, that points to the implementation class of the ServletContainerInitializer. 3.+ -
§ 8.2.4 Shared libraries / runtimes pluggability The ServletContainerInitializer’s onStartup
method get's a Set of Classes that either extend / implement the classes that the initializer expressed interest in or if it is annotated with any of the classes specified via the @HandlesTypes annotation. 3.+ -
Как? SPI tomcat |→ get javax.servlet.ServletContainerInitializer impl via SPI |→
get all MyInitializer classes (from @HandlesTypes) -
Как? SPI tomcat |→ get javax.servlet.ServletContainerInitializer impl via SPI |→
get all WebApplicationInitializer classes (from @HandlesTypes) org.springframework.web.WebApplicationInitializer -
Как? SPI tomcat |→ get javax.servlet.ServletContainerInitializer impl via SPI |→
get all WebApplicationInitializer classes (from @HandlesTypes) |→ call ServletContainerInitializer.onStartup(classes,servletCtx) according to @Order order -
@HandlesTypes(WebApplicationInitializer.class) public class SpringServletContainerInitializer implements ServletContainerInitializer { @Override public void
onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) -
@HandlesTypes(WebApplicationInitializer.class) public class SpringServletContainerInitializer implements ServletContainerInitializer { @Override public void
onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) ... AnnotationAwareOrderComparator.sort(initializers); ... -
@HandlesTypes(WebApplicationInitializer.class) public class SpringServletContainerInitializer implements ServletContainerInitializer { @Override public void
onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) ... AnnotationAwareOrderComparator.sort(initializers); ... initializers.forEach(initializer -> initializer.onStartup(ctx)); } -
public class WebStarter implements WebApplicationInitializer { @Override public void onStartup(ServletContext
servletContext) throws ServletException { AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext(); webContext.register(WebConfig.class); ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(webContext)); servlet.setLoadOnStartup(1); AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext(); appContext.register(AppConfig.class); servletContext.addListener(new ContextLoaderListener(appContext)); servlet.addMapping("/*"); } -
Как выглядит наш build.gradle plugins { id "org.springframework.boot" version "2.1.4.RELEASE"
} dependencies { compile 'org.springframework.boot:spring-boot-starter-web' } Добавляем зависимости -
Как выглядит наш build.gradle plugins { id "org.springframework.boot" version "2.1.4.RELEASE"
} dependencies { compile 'org.springframework.boot:spring-boot-starter-web' } Automatic Dependency Management No Version -
Как выглядит наш build.gradle plugins { id "org.springframework.boot" version "2.1.4.RELEASE"
} dependencies { compile 'org.springframework.boot:spring-boot-starter-web' } dependencyManagement { imports { mavenBom 'org.springframework.cloud:spring-cloud-dependencies:Greenwich.RELEASE' } } -
Анатомия SpringBoot Jar jar |- META-INF |- BOOT-INF |- libs
|- classes |- org |- springframework |- boot -
java -jar myapp.jar myapp.jar |- META-INF |- BOOT-INF |- libs
|- classes |- org |- springframework |- boot MANIFEST.MF ... Main-Class: ??? ... -
Анатомия SpringBoot Jar myapp.jar |- META-INF |- BOOT-INF |- libs
|- classes |- org |- springframework |- boot MANIFEST.MF ... Spring-Boot-Version: 1.5.3.RELEASE Implementation-Vendor: Pivotal Software, Inc. Main-Class: org.springframework.boot.loader.JarLauncher Start-Class:ru….ripper.OurMainClass Spring-Boot-Classes: BOOT-INF/classes/ Spring-Boot-Lib: BOOT-INF/lib/ ... -
myapp.jar |- META-INF |- BOOT-INF |- libs |- classes |-
org |- springframework |- boot Анатомия SpringBoot Jar MANIFEST.MF ... Spring-Boot-Version: 1.5.3.RELEASE Implementation-Vendor: Pivotal Software, Inc. Main-Class: org.springframework.boot.loader.JarLauncher Start-Class:ru….ripper.OurMainClass Spring-Boot-Classes: BOOT-INF/classes/ Spring-Boot-Lib: BOOT-INF/lib/ ... -
MANIFEST.MF ... Spring-Boot-Version: 1.5.3.RELEASE Implementation-Vendor: Pivotal Software, Inc. Main-Class: org.springframework.boot.loader.JarLauncher
Start-Class:ru….ripper.OurMainClass Spring-Boot-Classes: BOOT-INF/classes/ Spring-Boot-Lib: BOOT-INF/lib/ ... myapp.jar |- META-INF |- BOOT-INF |- libs |- classes |- org |- springframework |- boot Анатомия SpringBoot Jar JarLauncher -
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>conference...OurMainClass</mainClass> </configuration> </plugin> </plugins>
</build> MANIFEST.MF ... Start-Class: conference.spring.boot.ripper.OurMainClass ... -
Как выбирается mainClass если его не указать Spring boot plugin
сканирует проект – ищет мейны • если есть только один – то это он :) • если больше одного – смотрит где стоит @SpringBootApplication и выбирает его • если @SpringBootApplication нет или >1 – ошибка о множественных main при сборке -
Хочу executable jar: Maven <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration>
<executable>true</executable> </configuration> </plugin> </plugins> </build> springBoot { executable = true } Gradle bootJar { launchScript() } Spring boot 1.x.x Spring boot 2.x.x -
Внутренний мир executable Jar • Бабушка хочет чтобы жмя и
работало • windows “click click” • $ ./app.jar • ... -
Как выглядит Jar? Script 0xf4ra -> а это ZIP! jar
archive Начало файла -
Как выглядит Jar? Script 0xf4ra -> а это ZIP! jar
archive Начало файла Начало zip архива -
Где контекс? @SpringBootApplilcation class App { public static void main(String[]
args) { SpringApplication.run(App.class,args); } } -
Вот контекст! @SpringBootApplilcation class App { public static void main(String[]
args) { ApplicationContext context = SpringApplication.run(App.class,args); } } -
Давайте поговорим о контексте Малыш знает про ClassPathXmlApplicationContext А какие
контексты знаешь ТЫ? -
Это я решаю какой контекст создать Я до создания контекста
ещё много всего делаю, но об этом потом. SpringApplication -
Задание 1. Печатать предупреждение при вызове @Deprecated 2. Печатать время
исполнения методов @Benchmark 3. * Отправить email на адрес alarm.email если вызвали @Deprecated или @Benchmark -
Pointcut • execution • within • this • target •
args • bean • @annotation -
Пример @Aspect @Component public class TestAspect { @Pointcut("execution(* *.doSomething(..)) &&
args(list,..) ") public void callMethod(List<String> list) { ... } } -
Что за spring.factories ? § 44.1 Understanding auto-configured beans Under
the hood, auto-configuration is implemented with standard @Configuration classes. Additional @Conditional annotations are used to constrain when the auto-configuration should apply. Usually auto-configuration classes use @ConditionalOnClass and @ConditionalOnMissingBean annotations. This ensures that auto-configuration only applies when relevant classes are found and when you have not declared your own @Configuration. You can browse the source code of spring-boot-autoconfigure to see the @Configuration classes that we provide (see theMETA-INF/spring.factories file). -
@SpringBootApplication @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication { … -
@SpringBootApplication @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication { … -
@EnableAutoConfiguration @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import({EnableAutoConfigurationImportSelector.class}) public @interface EnableAutoConfiguration
{ String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; Class<?>[] exclude() default {}; String[] excludeName() default {}; } -
@EnableAutoConfiguration @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import({EnableAutoConfigurationImportSelector.class}) public @interface EnableAutoConfiguration
{ String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; Class<?>[] exclude() default {}; String[] excludeName() default {}; } -
@EnableAutoConfiguration @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import({EnableAutoConfigurationImportSelector.class}) public @interface EnableAutoConfiguration
{ String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; Class<?>[] exclude() default {}; String[] excludeName() default {}; } ImportSelector -
SpringFactoriesLoader static <T> List<T> loadFactories( Class<T> factoryClass, ClassLoader cl )
static List<String> loadFactoryNames( Class<?> factoryClass, ClassLoader cl ) -
CacheConfigurations private static final Map<CacheType, Class<?>> MAPPINGS; static { Map<CacheType,
Class<?>> mappings = new HashMap<CacheType, Class<?>>(); mappings.put(CacheType.GENERIC, GenericCacheConfiguration.class); mappings.put(CacheType.EHCACHE, EhCacheCacheConfiguration.class); mappings.put(CacheType.HAZELCAST, HazelcastCacheConfiguration.class); mappings.put(CacheType.INFINISPAN, InfinispanCacheConfiguration.class); mappings.put(CacheType.JCACHE, JCacheCacheConfiguration.class); mappings.put(CacheType.COUCHBASE, CouchbaseCacheConfiguration.class); mappings.put(CacheType.REDIS, RedisCacheConfiguration.class); mappings.put(CacheType.CAFFEINE, CaffeineCacheConfiguration.class); addGuavaMapping(mappings); mappings.put(CacheType.SIMPLE, SimpleCacheConfiguration.class); mappings.put(CacheType.NONE, NoOpCacheConfiguration.class); MAPPINGS = Collections.unmodifiableMap(mappings); } -
Где то внутри CacheAutoConfiguration for (int i = 0; i
< types.length; i++) { Imports[i] = CacheConfigurations.getConfigurationClass(types[i]); } return imports; -
Conditional и друзья @ConditionalOnBean @ConditionalOnClass @ConditionalOnCloudPlatform @ConditionalOnExpression @ConditionalOnJava @ConditionalOnJndi @ConditionalOnMissingBean
@ConditionalOnMissingClass @ConditionalOnNotWebApplication @ConditionalOnProperty @ConditionalOnResource @ConditionalOnSingleCandidate @ConditionalOnWebApplication ... -
Паззлер @Configuration @ConditionalOnWinterIsHere public class UndeadArmyConfiguration { @Bean public WinterUndeadArmy
cursedArmy() { return new WinterUndeadArmy(); } @Bean @ConditionalOnWinterIsHere public DragonGlassFactory dragonGlassFactory() { return new DragonGlassFactory(); } -
ConditionalOnPuzzler @Configuration public class КонфигурацияКазни { @Bean @ConditionalOnClass ({Мыло.class, Веревка.class})
@ConditionalOnMissingBean ({ФабрикаКазни. class}) public ФабрикаКазни виселицы() { return new ФабрикаВиселиц( "..."); } } -
ConditionalOnPuzzler @Configuration public class КонфигурацияКазни { @Bean @ConditionalOnClass ({Мыло.class, Веревка.class})
@ConditionalOnMissingBean ({ФабрикаКазни. class}) public ФабрикаКазни виселицы() { return new ФабрикаВиселиц( "..."); } @Bean @ConditionalOnClass ({Стул.class, Ток.class}) @ConditionalOnMissingBean ({ФабрикаКазни. class}) public ФабрикаКазни cтулья() { return new ФабрикаЭлектрическихСтульев( "вж вж"); } } -
ConditionalOnPuzzler @Configuration public class КонфигурацияКазни { @Bean @ConditionalOnClass ({Мыло.class, Веревка.class})
@ConditionalOnMissingBean ({ФабрикаКазни. class}) public ФабрикаКазни виселицы() { return new ФабрикаВиселиц( "..."); } @Bean @ConditionalOnClass ({Стул.class, Ток.class}) @ConditionalOnMissingBean ({ФабрикаКазни. class}) public ФабрикаКазни cтулья() { return new ФабрикаЭлектрическихСтульев( "вж вж"); } @Bean @ConditionalOnClass ({Гильотина.class, ХорошееНастроение. class}) @ConditionalOnMissingBean ({ФабрикаКазни. class}) public ФабрикаКазни гильотины() { return new ФабрикаГильотин( "хрусть хрусть"); } } -
ConditionalOnPuzzler @Configuration public class КонфигурацияКазни { @Bean @ConditionalOnClass ({Мыло.class, Веревка.class})
@ConditionalOnMissingBean ({ФабрикаКазни. class}) public ФабрикаКазни виселицы() { return new ФабрикаВиселиц( "..."); } @Bean @ConditionalOnClass ({Стул.class, Ток.class}) @ConditionalOnMissingBean ({ФабрикаКазни. class}) public ФабрикаКазни cтулья() { return new ФабрикаЭлектрическихСтульев( "вж вж"); } @Bean @ConditionalOnClass ({Гильотина.class, ХорошееНастроение. class}) @ConditionalOnMissingBean ({ФабрикаКазни. class}) public ФабрикаКазни гильотины() { return new ФабрикаГильотин( "хрусть хрусть"); } } 1. ClassDefNotFound ? 2. Так вообще нельзя, не компилируется 3. Будет работать 4. Будет отлично работать -
ConditionalOnPuzzler @Configuration public class КонфигурацияКазни { @Bean @ConditionalOnClass ({Мыло.class, Веревка.class})
@ConditionalOnMissingBean ({ФабрикаКазни. class}) public ФабрикаКазни виселицы() { return new ФабрикаВиселиц( "..."); } @Bean @ConditionalOnClass ({Стул.class, Ток.class}) @ConditionalOnMissingBean ({ФабрикаКазни. class}) public ФабрикаКазни cтулья() { return new ФабрикаЭлектрическихСтульев( "вж вж"); } @Bean @ConditionalOnClass ({Гильотина.class, ХорошееНастроение. class}) @ConditionalOnMissingBean ({ФабрикаКазни. class}) public ФабрикаКазни гильотины() { return new ФабрикаГильотин( "хрусть хрусть"); } } 1. ClassDefNotFound ? 2. Так вообще нельзя, не компилируется 3. Будет работать 4. Будет отлично работать -
OnPropertyCondition @Conditional(OnPropertyCondition.class) public @interface ConditionalOnProperty { String[] value() default {};
String prefix() default ""; String[] name() default {}; String havingValue() default ""; boolean matchIfMissing() default false; boolean relaxedNames() default true; } Что если нужно изменить? -
public class WebStarter implements WebApplicationInitializer { @Override public void onStartup(ServletContext
servletContext) throws ServletException { AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext(); webContext.register(WebConfig.class); ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(webContext)); servlet.setLoadOnStartup(1); AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext(); appContext.register(AppConfig.class); servletContext.addListener(new ContextLoaderListener(appContext)); servlet.addMapping("/*"); } -
public class WebStarter implements WebApplicationInitializer { @Override public void onStartup(ServletContext
servletContext) throws ServletException { AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext(); webContext.register(WebConfig.class); ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(webContext)); servlet.setLoadOnStartup(1); AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext(); appContext.register(AppConfig.class); servletContext.addListener(new ContextLoaderListener(appContext)); servlet.addMapping("/*"); } -
public class WebStarter implements WebApplicationInitializer { @Override public void onStartup(ServletContext
servletContext){ SpringApplication.run(RipperApplication.class); } } -
public class WebStarter implements WebApplicationInitializer { @Override public void onStartup(ServletContext
servletContext) { SpringApplication.run(RipperApplication.class); } } @SpringBootApplication public class RipperApplication { public static void main(String[] args) { SpringApplication.run(RipperApplication.class, args); } } -
public class WebStarter implements WebApplicationInitializer{ @Override public void onStartup(ServletContext servletContext)
throws ServletException { SpringApplication.run(RipperApplication.class); } } Tomcat в Tomcat`е -
§ 85.1 Create a deployable war file @SpringBootApplication public class
Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder app) { return app.sources(Application.class); } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } } -
§ 85.1 Create a deployable war file @SpringBootApplication public class
Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder app) { return app.sources(Application.class); } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } } -
§ 85.1 Create a deployable war file @SpringBootApplication public class
Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder app) { return app.sources(Application.class); } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } } Работает по разному -
§ 85.1 Create a deployable war file @SpringBootApplication public class
Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder app) { return app.sources(Application.class); } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } } -
§ 85.1 Create a deployable war file @SpringBootApplication public class
Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder a) { return application.sources(Application.class); } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } } Никогда не запустится в tomcat Только java -jar -
§ 85.1 Create a deployable war file @SpringBootApplication public class
Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder a) { return application.sources(Application.class); } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } } Без main не соберется см. maven/gradle плагины Обязательно -
§ 85.1 Create a deployable war file @SpringBootApplication public class
Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder a) { return application.sources(Application.class); } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } } Опционально -
§ 85.1 Create a deployable war file @SpringBootApplication public class
Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder a) { return application.sources(Application.class); } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } } Никогда не запустится в embedded режиме Только в Tomcat контейнере Опционально -
Анатомия War .war |- META-INF |- WEB-INF |- lib |-
classes |- org/springframework/boot/loader |- WarLauncher and friends -
А как убрать tomcat из tomcat? If you are using
a version of Gradle that supports compile only dependencies (2.12 or later), you should continue to use providedRuntime. Among other limitations, compileOnly dependencies are not on the test classpath so any web-based integration tests will fail. -
Анатомия War .war |- META-INF |- WEB-INF |- lib |-
lib-provided |- classes |- org/springframework/boot/loader |- WarLauncher and friends -
Анатомия SpringBoot Jar/War jar |- META-INF |- BOOT-INF |- libs
|- classes |- org/springframework/boot/loader |- JarLauncher and friends war |- META-INF |- WEB-INF |- lib |- lib-provided |- classes |- org/springframework/boot/loader |- WarLauncher and friends -
@RestController("/examine") Это имя spring bean, не http path И это
даже может работать: • Если нет ни одного контроллера с путём (всегда будет вызываться) • Если потом указали полный путь в @RequestMapping -
@RequestMapping и его братья Управляет маршрутизацией запросов в метод контроллера.
Маршрутизирует по: • name/value – сам http path • method – http method • params • headers -
@RequestMapping и его братья @PostMapping("/examine") public CheckedExam ex`( @RequestBody SolvedExam
title) { } @RequestMapping (path = "/examine", method = POST) public CheckedExam ex2( @RequestBody SolvedExam title) { } @RequestMapping (path = "/examine", method = POST, headers = {"my-app=appid"}) public CheckedExam ex3( @RequestBody SolvedExam title) { } @GetMapping(path = "/examine", headers = {"content-type=application/json"}) public CheckedExam ex3() { } @GetMapping(path = "/examine", produces = MimeTypeUtils. APPLICATION_JSON_VALUE) public CheckedExam ex3() { } -
@RequestMapping и его братья @PostMapping("/examine") public CheckedExam ex`( @RequestBody SolvedExam
title) { } @RequestMapping (path = "/examine", method = POST) public CheckedExam ex2( @RequestBody SolvedExam title) { } @GetMapping(path = "/examine", headers = {"content-type=application/json"}) public CheckedExam ex3() { } @GetMapping(path = "/examine", produces = APPLICATION_JSON_VALUE) public CheckedExam ex3() { } @GetMapping(path = "/examine", produces = APPLICATION_JSON_VALUE) public CheckedExam ex4() { } -
@RequestMapping и его братья @PostMapping("/examine") public CheckedExam ex`( @RequestBody SolvedExam
title) { } @RequestMapping (path = "/examine", method = POST) public CheckedExam ex2( @RequestBody SolvedExam title) { } @GetMapping(path = "/examine", headers = {"content-type=application/json"}) public CheckedExam ex3() { } @GetMapping(path = "/examine", produces = APPLICATION_JSON_VALUE) public CheckedExam ex3() { } @GetMapping(path = "/examine", produces = APPLICATION_JSON_VALUE) public CheckedExam ex4() { } -
@RequestMapping и его братья //curl -XPOST /examine -d '{ "title":
{..} }' @PostMapping("/examine") public CheckedExam ex`( @RequestBody SolvedExam exam) { } //curl -XGET /examine/ mytitle @GetMapping("/examine/{title}") public CheckedExam ex3( @PathVariable String title) { } //curl -XGET /examine/mytitle ?debug=true @GetMapping("/examine/{title}") public CheckedExam ex3( @PathVariable String title, @RequestParam Boolean debug) { } -
Controllers endpoints in logs since Spring 5 logging.level: //print mapped
controllers org.springframework.web.servlet.mvc.method.annotation: TRACE web: DEBUG //print requests to console -
Задание 0 Напишем стартер DoD: 1. Все контроллеры помеченые @FrontendController
аннотацией должны обворачивать возвращаемый результат в дополнительный Json { "result": { оригинальный_json } } 2. https://github.com/lavcraft/spring-boot-and-cloud-ripper-2019 3. -
Задание 1. Напишем Экзаминатора public static void main(String[] args){ SpringApplication.run(
ExaminatorApplication.class, args); } -
{ "География":5, "Физика" :3 } Физика Математика Теология Не грешно
ли лезть в атом? Теорема Пифагора Неравенство Коши E=? Количество вопросов Количество вопросов Экзаминатор -
С чего начинают строить микросервис →Контроллеры →Сервисы →Dao →Model –
поскольку модель используется на всех слоях, пожалуй лучше начинать с неё -
in: { "student": "Борисов Евгений", "title": "Экзамен на JokerConf", "sections":
[{ "title": "Java", "description": "простые вопросы по java", "exercises": [ { "question": "разница между spring string и swing", "answer": "без spring`а не обойтись" }, { "question": "разница между final finally finalize", "answer": "за finalize отрывают руки" } ]}, { "title": "философия", "description": "сложные вопросы по философии", "exercises": [{ "question": "В чем смысл жизни", "answer": "42" }, { "question": "Что раньше, яйцо или курица", "answer": "петух" }] }] } out: { "mark": 99, "title": "Экзамен на JokerConf", "sections": [{ "title": "Java", "description": "простые вопросы по java", "exercises": [ { "question": "разница между spring string и swing", "answer": "без spring`а не обойтись" }, { "question": "разница между final finally finalize", "answer": "за finalize отрывают руки" } ]}, { "title": "философия", "description": "сложные вопросы по философии", "exercises": [{ "question": "В чем смысл жизни", "answer": "42" }, { "question": "Что раньше, яйцо или курица", "answer": "петух" }] }] } -
Data model - задание 1.1* Придумайте архитектуру модели, которая позволит
написать Сервис: - принимающий на вход объект SolvedExam - отдающий CheckedExam с оценкой - Должны проходить тесты @Test public void checkExamineContract() throws Exception { ... mockMvc.perform(post("/examine")) ... } Use @RestController and @RequestMapping > @*Mapping Luke -
Data model - задание 1.1* Придумайте архитектуру модели, которая позволит
написать Сервис: - принимающий на вход объект SolvedExam - отдающий CheckedExam с оценкой - Смотрите в src/test/resources/*.json - Должны проходить тесты @Test public void checkExamineContract() throws Exception { ... mockMvc.perform(post("/examine")) ... } Use @RestController and @RequestMapping > @*Mapping Luke -
Lombok – composition / delegate and friends Annotation Processor Работает
на этапе компиляции Генерит код, чтобы мы не писали Делает джаву более похожим на нормальный язык -
Про lombok, модели и не только @Data – POJO (@Getter,
@Setter, @ToString, @EqualsAndHashcode) @Value – immutable POJO @AllArgumentConstruct(onConstructor = @_(@Autowired)) -
Про lombok, модели и не только @Data – POJO (@Getter,
@Setter, @ToString, @EqualsAndHashcode) @Value – immutable POJO @AllArgumentConstruct(onConstructor = @_(@Autowired)) @RequireArgumentConstructor /@NoArgumentConstructor @Builder / @Singular @Delegate – примерно как в груви @SneakyThrows @Slf4j / @Log4j / … -
Как Джексон пишет в джейсон 1. Использует Java Getters a.
Методы начинающиеся с Get 2. @JsonIgnore – игнорируем Getter 3. Нет ни одного Getter – падает -
Как Джексон пишет в объект 1. Нет конструктора с @ConstructProperies
→ выставляет через Setters → если нет Setter и есть Getter – выставляет напрямую в филды → это все только при наличии пустого конструктора 2. Есть конструктор с @ConstructProperies → выставляет значение через него 3. После зачем то вызовет все геттеры * Но если есть то @JsonIgnore всё по другому * Это поведение по умолчанию -
→ Если вы настраиваете руками: ObjectMapper mapper = new ObjectMapper()
.registerModule( new ParameterNamesModule()) .registerModule( new Jdk8Module()) .registerModule( new JavaTimeModule()); → Или так: mapper.findAndRegisterModules(); Не забыть зависимости: compile 'com.fasterxml.jackson.module:jackson-module-parameter-names' compile 'com.fasterxml.jackson.datatype:jackson-datatype-jdk8' compile 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310' C последних версий есть поддержка Java8 -
Как Spring MVC работает с Джексоном Напишите метод который принимает
json и класс, а возвращает объект данного класса Пробуем использовать objectMapper Jackson2 -
Кто использует Jackson в мире Spring MVC 1. ClassLoader 2.
Dispatcher Servlet 3. Tomcat 4. BeanPostProcessor -
Кто использует Jackson в мире Spring MVC 1. ClassLoader 2.
Dispatcher Servlet 3. Tomcat 4. BeanPostProcessor -
Задание 2 Микросервис – Теологии 1. Добавлять вопросы по теологии
… (CRUD) 2. Получать нужное количество рандомальных вопросов 3. Тест должен проходить @Test public void should_return_random_exercise() throws Exception { mvc.perform(get("/exercise/random?count=3") .contentType( APPLICATION_JSON) ) … Use JpaRepository and @RequestMapping Luke -
{ "География":5, "Физика" :3 } Физика Математика Теология Не грешно
ли лезть в атом? Теорема Пифагора Неравенство Коши ваы Количество вопросов Количество вопросов Экзаминатор Person p = restTemplate.getForObject("/{name}/details", Person.class, name); Для связи сервисов используем RestTemplate -
Конфликт портов — relaxed properties 1. server.port в application.properties 2.
export SERVER_PORT=8081 3. java -jar --server.port=8081 4. SPRING_APPLICATION_JSON = '{"server":{"port":8081}}' -
in: { "student": "Борисов Евгений", "title": "Экзамен на JokerConf", "sections":
[{ "title": "Java", "description": "простые вопросы по java", "exercises": [ { "question": "разница между spring string и swing", "answer": "без spring`а не обойтись" }, { "question": "разница между final finally finalize", "answer": "за finalize отрывают руки" } ] }, { "title": "философия", "description": "сложные вопросы по философии", "exercises": [{ "question": "В чем смысл жизни", "answer": "42" }, { "question": "Что раньше, яйцо или курица", "answer": "петух" }] }] } -
Дальше пишем Entity + Repository Which repositories get exposed by
defaults? Name Description DEFAULT Exposes all public repository interfaces but considers @Repository/@RestResource’s `exported flag ALL Exposes all repositories independently of type visibility and annotations ANNOTATION Only repositories annotated with @Repository/@RestResource are exposed, unless their exported flag is set to false VISIBILITY Only public repositories annotated are exposed -
Как поменять стратегию @Component public class MyWebConfiguration extends RepositoryRestConfigurerAdapter {
@Override public void configureRepositoryRestConfiguration( RepositoryRestConfiguration config) { config.setRepositoryDetectionStrategy( ALL); } } -
Как задать URL @Configuration class CustomRestMvcConfiguration { @Bean public RepositoryRestConfigurer
repositoryRestConfigurer() { return new RepositoryRestConfigurerAdapter() { @Override public void configureRepositoryRestConfiguration( RepositoryRestConfiguration config) { configuration.setBasePath( "/api") } }; } } -
Как задать URL @Configuration class CustomRestMvcConfiguration { @Bean public RepositoryRestConfigurer
repositoryRestConfigurer() { return new RepositoryRestConfigurerAdapter() { @Override public void configureRepositoryRestConfiguration( RepositoryRestConfiguration config) { configuration.setBasePath( "/api") } }; } } Или в том же RepositoryRestConfigurerAdapter прописать в application.properties - spring.data.rest.base-path=/api -
Spring Data Rest official supports →Spring Data JPA →Spring Data
MongoDB →Spring Data Neo4j →Spring Data GemFire →Spring Data Cassandra -
@RepositoryRestResource @RepositoryRestResource (collectionResourceRel = "people", path = "people") public interface
PersonRepository extends MongoRepository<Person, String> { @RestResource(path = "byname") List<Person> findByLastName(@Param( "name") String name); } -
URL’s и методы localhost:8080/exercise – список всех (GET) localhost:8080/exercise/1 –
дай человека с айдишником 1 (GET) localhost:8080/exercise/1 – стереть с айдишником 1 (DELETE) localhost:8080/exercise/1 – заменить с айдишником 1 (PUT) localhost:8080/exercise/1 – проапдэйтить с айдишником 1 (PATCH) localhost:8080/exercise/search/findByName?name=Lanister -
{ "География":5, "Физика" :3 } Физика Математика Теология Не грешно
ли лезть в атом? Теорема Пифагора Неравенство Коши ваы Количество вопросов Количество вопросов Экзаминатор -
Задание 3 Связать сервисы Экзаменатора и Предметы • Запустить и
проверить самим • Должен отдаваться запрос с ответами другого сервиса { "География":5, "Физика" :3 } -
--server.port Конфликт портов решается с помощью relaxed properties export SERVER_PORT=8081
java -jar --server.port=8081 SPRING_APPLICATION_JSON = '{"server":{"port":8081}}' -
RestTemplate • you can create it even with new /
or inject configured bean • postForEntity / postForObject/ getForEntity / getForObject restTemplate.getForObject( "http://"+serviceName+"/exercice/random?count=" + number, Exercice[].class); • exchange restTemplate.exchange(url.toString(), HttpMethod.POST, entity, String.class); -
Подход №1 - общий код Зачем разбивать микросервис на модули?
→ Java API для сервисов → фиксация контракта на уровне зависимостей языка → утилитарная функция, избавления от бойлерплейта -
Подход №1 - общий код project |- project-sdk |- project-app
|- project-... -
Подход №1 - общий код project |- project-sdk |- project-app
|- project-api |- project-domain |- project-... Пфф -
Подход №1 - общий код project |- project-sdk |- project-app
|- project-api |- project-domain |- project-... Пфф KISS -
Подход №2 - общий контракт → разделение кода и контракта
→ поставка контракта отдельно -
Обратимся к истории → REST подход ◦ анархия и рекомендации
→ RPC подход ◦ -
Обратимся к истории → REST подход ◦ анархия и рекомендации
→ RPC подход ◦ jax-ws/jax-rpc ◦ corba ◦ json rpc ◦ ◦ -
Обратимся к истории → REST подход ◦ анархия и рекомендации
→ RPC подход ◦ jax-ws/jax-rpc ◦ corba ◦ json rpc ◦ thrift ◦ protobuf/grpc ◦ etc -
Задание 5 • пишем SDK для вызова микросервиса по теологии
• и тесты для него • тестируем контракт • тестируем взаимодействие ◦ WireMock/Spring MockServer ◦ Spring Boot Test ◦ Context Scanning behaviour Тест SDK Тест Контракта Тест Взаимодействия -
{ "География":5, "Физика" :3 } Физика Математика Теология Не грешно
ли лезть в атом? Теорема Пифагора Неравенство Коши Энтропия не? Количество вопросов Количество вопросов Экзаминатор -
{ "География":5, "Физика" :3 } Физика Математика Теология Теорема Пифагора
Неравенство Коши ваы Количество вопросов Количество вопросов Экзаминатор Бог Не грешно ли лезть в атом? -
Матмематика – сервис • Сделать новый модуль • Реализовать метод
"/exercise/random" • Возвращать список автогенерируемых упражнение (как в Теологии) -
Как воткнуть в Examinator math-service? exercises: urls: "theology" : "http://localhost:8080/"
"math" : "http://localhost:8082/" Потому что на 8081 Examinator -
Как воткнуть в Examinator math-service? exercises: urls: "theology" : "http://localhost:8080/"
"math" : "http://localhost:8082/" "examinator": "http://localhost:8081/" "..." : "http://localhost:8083/" Service Registry в application.yml -
{ "География":5, "Физика" :3 } Физика Математика Количество вопросов Количество
вопросов Экзаминатор Экзаминатор Теология Service Registry -
{ "География":5, "Физика" :3 } Физика Математика Количество вопросов Количество
вопросов Экзаминатор Экзаминатор Теология Service Registry Clients Server -
Что хранится в Service Registry? • serviceId • Ip адрес
и порт • Данные о хелсчеках • Метаданные ◦ Данные о геозонах ◦ Пользовательские данные -
/actuator/health { "status": "UP", "details": { "diskSpace": { "status": "UP",
"details": { "total": 499963174912, "free": 354837377024, "threshold": 10485760 } }, "refreshScope": { "status": "UP" }, …. -
Eureka Server and Client compile 'org.springframework.cloud:spring-cloud-starter-eureka-server' compile 'org.springframework.cloud:spring-cloud-starter-eureka' С Greenwich
релиза compile 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' compile 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server' Spring Boot 1.x.x Spring Boot 2.x.x -
Собственный Eureka Server @EnableEurekaServer @SpringBootApplication public class EurekaServer { public
static void main(String[] args) { SpringApplication.run(EurekaServer.class, args); } } server.port: 8761 spring.application.name: registry eureka: client.register-with-eureka: false server.enable-self-preservation: false -
Переводим на Eureka • Создаём модуль eureka-server compile 'org.springframework.cloud:spring-cloud-starter-eureka-server' compile
'org.springframework.cloud:spring-cloud-starter-eureka' Or compile 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server' compile 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' -
Переводим на Eureka • Подключаем новый bom enforcedPlatform( "org.springframework.cloud: spring-cloud-dependencies:Greenwich.RELEASE"),
• Создаём модуль eureka-server compile 'org.springframework.cloud:spring-cloud-starter-eureka-server' Or compile 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server' • Интегрируем клиента (examinator-service, theology-service, math-service) compile 'org.springframework.cloud:spring-cloud-starter-eureka' Or compile 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' -
Переводим на Eureka @EnableDiscoveryClient vs @EnableEurekaClient eureka.client.service-url.default-zone: http://127.0.0.1:8761/eureka/ spring.application.name: EXAMINATOR
@Никаких Аннотация не нужно в 2хх eureka.client.service-url.default-zone: http://127.0.0.1:8761/eureka/ spring.application.name: EXAMINATOR Spring Boot 1.x.x Spring Boot 2.x.x -
@EnableDiscoveryClient Будет включен по умолчанию при добавлении стартера c Edgware
spring-cloud release train application.yml: server.port: 8081 spring.application.name: examinator eureka.client.service-url.defaultZone:http://localhost:8671/eureka -
@EnableEurekaServer Будет включен по умолчанию при добавлении стартера c Edgware
spring-cloud release train application.yml: server.port: 8761 spring.application.name: registry eureka: client.register-with-eureka= false -
Кто это у нас там спрятался? Смотрим какие сервисы загрузились
$ http :8082/health { "description": "Remote status from Eureka server", "status": "DOWN" } { "description": "Spring Cloud Eureka Discovery Client", "status": "UP" } Spring Boot 1.x.x -
Кто это у нас там спрятался? Выключаем security для управляющий
API management: security: enabled: false Теперь $ http :8082/health Spring Boot 1.x.x -
{ "description": "Spring Cloud Eureka Discovery Client", "discoveryComposite": { "description":
"Spring Cloud Eureka Discovery Client", "discoveryClient": { "description": "Spring Cloud Eureka Discovery Client", "services": [ "examinator-service", "math-service", "theology-service" ], "status": "UP" }, "eureka": { "applications": { "EXAMINATOR-SERVICE": 1, "MATH-SERVICE": 1, "THEOLOGY-SERVICE": 1 }, "description": "Remote status from Eureka server", "status": "UP" }, "status": "UP" }, "diskSpace": { "free": 190254260224, "status": "UP", "threshold": 10485760, "total": 499055067136 }, ... Spring Boot 1.x.x -
Кто это у нас там спрятался? application.yml management: endpoints: web:
exposure: include: '*' Spring Boot 2.x.x -
Кто это у нас там спрятался? Смотрим какие сервисы загрузились
$ http :8082/actuator/health { "status": "UP" } $ http :8082/actuator/metrics ... $ http :8082/actuator ... Spring Boot 2.x.x -
True Discovery • Написать контроллер, который возвращает все зарегистрированные сервисы
• Запустить несколько сервисов одного типа, посмотреть результат @Autowired private DiscoveryClient discoveryClient; discoveryClient.getServices() discoveryClient.getInstances("theology") -
True Discovery • Включить логику резолва сервиса в адресе запроса
Use @LoadBalanced or LoadBalancerInterceptor Luke -
Health checks unavailable window marathon window app available http available
available window starting -
Health checks unavailable window marathon window app available http available
started available window starting working -
Self preservation Service Registry 2 Service A Instance 1 Service
B Instance 1 Service A Instance 2 Service B Instance 2 Service Registry 1 -
Self preservation Service Registry 2 Service A Instance 1 Service
B Instance 1 Service A Instance 2 Service B Instance 2 Service Registry 1 -
Discovery и Load Balancing Две стороны одного и того же
Server Side vs Client Side -
357 Service Client Registry-aware HTTP Client Service Registry Service Instance
1 Service Instance N Service Instance ... Load balance request Client side discovery Ribbon + Eureka Discovery client -
358 Service Client Service Registry Service Instance 1 Service Instance
N Service Instance ... Load balance request Router/Proxy Server side discovery -
Feign Client с обратной стороны стороны @RestController @RequestMapping(value = "/v0/forms/latestByUserId")
public class FormsController { @GetMapping Form get(@RequestHeader("x-userid") String userId) { return new Form(..) } } -
Feign Client с другой стороны @RestController @RequestMapping(value = "/v0/forms/latestByUserId") public
class FormsController { @GetMapping Form get(@RequestHeader("x-userid") String userId) { return new Form(..) } } -
Feign Client @FeignClient( name = "myApplicationName", url = "${config.myApplicationName}") @RequestMapping(value
= "/v0/forms/latestByUserId") public interface FormsClient { @GetMapping Form get(@RequestHeader("x-userid") String userId); } -
Feign Client @FeignClient( name = "myApplicationName", url = "${config.myApplicationName}") @RequestMapping(value
= "/v0/forms/latestByUserId") public interface FormsClient { @GetMapping Form get(@RequestHeader("x-userid") String userId); } -
Блеск и нищета RestTemplate restTemplate.exchange( "/forms", HttpMethod.GET, HttpEntity.newInstance(headers), Form[].class).body restTemplate.exchange(
"/forms", HttpMethod.GET, HttpEntity.newInstance(headers), new ParameterizedTypeReference<List<Form>>() {}).body -
Применимость FeignClient – the best если есть готовы контракт с
которым есть интеграция * Но есть ньюансы RestTemplate — более общий инструмент, подойдёт в большем спектре случай, но решение будет читаться хуже и будет больше технических деталей -
Принципы SOA 373 1. Standardized service contract 2. Loose coupling
3. Encapsulation 4. Reusability 5. Autonomy 6. Statelessness 7. Discoverability -
Принципы SOA 374 1. Standardized service contract 2. Loose coupling
3. Encapsulation 4. Reusability 5. Autonomy 6. Statelessness 7. Discoverability -
Fluent annotations 375 @Getter // generate getters @Setter // generate
setters @Aspect // we are an aspect @ToString // generate toString() @EnableWs // SOAP is so enterprisy, we definitely need it @Endpoint // Seriously, just read above @EnableWebMvc // we want MVC @EnableCaching // and we want to cache stuff @Configuration // this class can configure itself @RestController // we want some REST @XmlRootElement // this component is marshallable @EnableWebSocket // we want web socket, it's so new-generation @RedisHash("cat") // this class is an entity saved in redis @EnableScheduling // we want scheduled tasks @EnableWebSecurity // and some built-in security @NoArgsConstructor // generate no args constructor @ContextConfiguration // we want context configuration for unit testing @SpringBootApplication // this is a Sprint Boot application @Accessors(chain = true) // getters/setters are chained (ala jQuery) @EnableAspectJAutoProxy // we want AspectJ auto proxy @EnableAutoConfiguration // and auto configuration -
Парадокс централизации Чтобы эффективно разрабатывать распределённые приложения, нам нужны очень
хорошие централизованные библиотеки и инструменты Например: логирование, health-checking, метрики, обработка типовых ошибок, автодокументирование 376 -
Парадокс централизации Чтобы эффективно разрабатывать распределённые приложения, нам нужны очень
хорошие централизованные библиотеки и инструменты Но: не выносите бизнес-логику или доменные объекты! Не размывайте бизнес-контекст вашего API 377 -
Что лежит внутри • application.yml • application-test.yml • examinator.yml •
examinator-dev.yml -
Your own Config Server • Создать модуль config-server клиент implementation
'org.springframework.cloud:spring-cloud-starter-config' сервер implementation 'org.springframework.cloud:spring-cloud-config-server' @EnableConfigServer spring: cloud: config: server: git: uri: адрес репозитория -
Your own Config Server Можно проверить конфиги по адресу: http://host:port/{label}/{application_name}-{profile}.yml
или • /{label}/{name}-{profiles}.yml • /{name}-{profiles}.yml • /{name}-{profiles}.yaml • /{name}/{profile}/{label} • ... -
Проблема курица и яйца Откуда брать координаты eureka? • из
сonfig-server (для всех же одинаковые) • из локальных настроек (ENV/*.yml/etc) Откуда брать координаты сonfig-server • из eureka • из локальных настроек (ENV/*.yml/etc) -
Config Server Discovery Через Service Discovery App Instance #0 App
Instance #N Config Server По прямой ссылке Eureka -
Config Server Discovery Через Service Discovery App Instance #0 App
Instance #N Eureka Config Server register on start get Config Server by name -
Config Server Discovery Через Service Discovery App Instance #0 App
Instance #N Eureka Config Server register on start return config server instances location get Config Server by name -
Config Server Discovery Через Service Discovery App Instance #0 App
Instance #N Eureka Config Server register on start return config server instances location get Config Server by name get configs for App -
Config Server Discovery По прямой ссылке App Instance #0 App
Instance #N Config Server get configs for App Http Load Balancer -
Config Client • интегрируем config-server и *-service через eureka •
включаем/отключаем management.security -
Начнём с примера @RestController @RefreshScope public class TestController { @Value("${foo.bar}")
String test; @GetMapping("/foo") public String getFooBar() { return test; } } -
Начнём с примера @RestController @RefreshScope public class TestController { @Value("${foo.bar}")
String test; @GetMapping("/foo") public String getFooBar() { return test; } } -
Начнём с примера @RestController @RefreshScope public class TestController { @Value("${foo.bar}")
String test; @GetMapping("/foo") public String getFooBar() { return test; } } -
Три простых шага 1. Ставим @RefreshScope над бином который нужно
обновлять 2. Обновляем в config server foo.bar: some val a. Можно не править а дёрнуть /env если есть actuator 3. Дёргаем у приложения /refresh a. Для этого нужен actuator -
Физика Математика Экзаминатор Экзаминатор Теология Теология Config Server ALL APP
Discovery Server ALL APP -
Физика Математика Экзаминатор Экзаминатор Теология Теология Queue Config Server ALL
APP Discovery Server ALL APP ALL APP -
Spring Cloud Bus dependencyManagement { imports { mavenBom 'org.springframework.cloud:spring-cloud-bus:2.1.1.RELEASE' }
} dependencies { compile 'org.springframework.cloud:spring-cloud-starter-bus-amqp' } -
Теперь достаточно /refresh на config-server 1. Все приложения обновят конфигурации
при получении refresh ивента в rabbitmq -
Теперь достаточно /refresh на config-server 1. Все приложения обновят конфигу
при получении refresh ивента в rabbitmq 2. Для автоматизации можно использовать config-monitor + git webhook compile 'org.springframework.cloud:spring-cloud-config-monitor' 3. Не забывать @RefreshScope -
spring-cloud-config-monitor Config Server Экзаминатор Экзаминатор GitHub commit Config Monitor webhook
Queue refresh event Теология Теология Теология ... auto /refresh on event -
Физика Математика Теология Теология Queue Экзаминатор Config Server ALL APP
Discovery Server ALL APP ALL APP -
Физика Математика Экзаминатор Экзаминатор Теология Теология Queue Config Server ALL
APP Discovery Server ALL APP ALL APP -
Физика Математика Экзаминатор Экзаминатор Теология Теология Queue Config Server ALL
APP Discovery Server ALL APP ALL APP Экзаминатор -
Физика Математика Экзаминатор Экзаминатор Теология Теология Gateway Server Queue Config
Server ALL APP Discovery Server ALL APP ALL APP -
Зависимости Spring Cloud Gateway dependencies { compile 'org.springframework.cloud:spring-cloud-starter-gateway' //for webflux
compile 'org.springframework.cloud:spring-cloud-gateway-webflux' //or for mvc compile 'org.springframework.cloud:spring-cloud-gateway-mvc' } Spring boot 2.x.x -
Зависимости Spring Cloud Gateway dependencies { compile 'org.springframework.cloud:spring-cloud-starter-gateway' //for webflux
compile 'org.springframework.cloud:spring-cloud-gateway-webflux' //or for mvc compile 'org.springframework.cloud:spring-cloud-gateway-mvc' } application.yml: spring: cloud.gateway.discovery.locator.enabled: true Spring boot 2.x.x -
Почему стоит мигрировать? • Zuul устарел и почти не поддерживается,
Zuul 2 ждали долго • Zuul не совместим с Spring Boot 2.1 • Spring Cloud Gateway работает на Netty • Spring Cloud Gateway имеет сильно больше фильтров “из коробки” -
Роутинг в конфигурации zuul zuul: ignoredServices: '*' routes: student: path:
/exam/** stripPrefix: true serviceId: examinator -
Zuul.Фильтры @Component public class ChangeSearchFilter extends ZuulFilter { public String
filterType() { return PRE_TYPE; } public int filterOrder() { return PRE_DECORATION_FILTER_ORDER + 1;} public boolean shouldFilter() { HttpServletRequest request = RequestContext.getCurrentContext() .getRequest(); return request.getRequestURI().startsWith( "/exam") && StringUtils.isEmpty(request.getHeader("studentId")); } ... -
Zuul.Фильтры @Component public class ChangeSearchFilter extends ZuulFilter { ... public
Object run() throws ZuulException { RequestContext ctx = RequestContext. getCurrentContext(); ctx.addZuulRequestHeader( "Request-time", Long.toString(System.currentTimeMillis())); return null; } } -
Роутинг в конфигурации gateway spring: cloud: gateway: routes: - id:
math uri: lb://math predicates: - Path=/math/** -
Gateway.Фильтры @Bean public RouteLocator route(RouteLocatorBuilder builder) { return builder.routes() .route(r
-> r.host( "**.some.org").and().path("/exam") .filters(f ->f.addResponseHeader( "Request-time", currentTime)) .uri("lb://examinator") ).build(); } -
Gateway • Создаем проект с gateway • Подключаем его к
service-discovery • Пишем конфигурацию для роутинга в examinator -
Сказка о балансировщике который не смог External LB Local Node
LB App Level LB -
Сказка о балансировщике который не смог External LB Local Node
LB App Level LB Zuul haproxy F5 App Type A Client Side LB App Type A Client Side LB App Type A Client Side LB -
Сказка о балансировщике который не смог External LB Local Node
LB App Level LB App Type A Client Side LB App Type A Client Side LB App Type A Client Side LB App Type B Client Side LB App Type B Client Side LB App Type B Client Side LB Zuul haproxy F5 SSL/DDOS/ Protection/BGP/Publication Data Locality/Cluster HA/ Cluster Health App Level LB/Metrics/ Advanced Routing/Auth -
Сказка о балансировщике который не смог External LB Local Node
LB App Level LB App Type A Client Side LB App Type A Client Side LB App Type A Client Side LB App Type B Client Side LB App Type B Client Side LB App Type B Client Side LB Zuul haproxy F5 SSL/DDOS/ Protection/BGP/Publication Data Locality/Cluster HA/ Cluster Health App Level LB/Metrics/ Advanced Routing/Auth -
Сказка о балансировщике который не смог External LB Local Node
LB App Level LB App Type A Client Side LB App Type A Client Side LB App Type A Client Side LB App Type B Client Side LB App Type B Client Side LB App Type B Client Side LB Zuul haproxy F5 SSL/DDOS/ Protection/BGP/Publication App Level LB/Metrics/ Advanced Routing/Auth Discovery service Discovery service Discovery service Data Locality/Cluster HA/ Cluster Health -
434 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service 5мс -
435 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service 300мс -
436 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service 300мс -
437 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service 300мс -
438 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service 300мс -
440 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service 300мс -
441 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service 300мс Open -
442 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service 300мс Half-Open -
443 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service 5мс Half-Open -
444 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service 5мс -
Из чего состоит Hystrix • Механизм Circuit breaker • Механизм
Timeout • Механизм BulkHead -
Rent Service Payment Service Security Service Blockchain Service Insurance Service
threadpool size timeout x = 10 настроек -
Rent Service Payment Service Security Service Blockchain Service Insurance Service
threadpool size connection timeout read timeout timeout x = 20 настроек -
452 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service Open -
453 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service Open Надо подкрутить таймауты! -
454 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service -
455 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service Open -
456 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service Open Надо подкрутить таймауты! -
458 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service Open Да блин! -
Отличия • Более легковесный (из коробки тянет только vavr) •
Не пытается сам управлять пулом потоков -
Отличия • Более легковесный (из коробки тянет только vavr) •
Не пытается сам управлять пулом потоков • Нет request collapser • Есть rate limiter • Есть retry -
Отличия • Более легковесный (из коробки тянет только vavr) •
Не пытается сам управлять пулом потоков • Нет request collapser • Есть rate limiter • Есть retry • Удобное оборачивание методов “слоями” в функциональном стиле или набором аннотаций • Собранные “обертки” можно переиспользовать -
Gateway • Делаем так, чтобы один из сервисов(java,math) возращал ошибку
в 50% случаев • Подключаем hystrix и настраиваем для него cicruitbreaker на закрытие • Пишем конфигурацию для роутинга в examinator -
Gateway + Hystrix + Dashboard + Discovery dependencies { compile
'org.springframework.boot:spring-boot-starter-web' compile 'org.springframework.boot:spring-boot-starter-actuator' compile 'org.springframework.cloud:spring-cloud-starter-zuul' compile 'org.springframework.cloud:spring-cloud-starter-eureka' compile 'org.springframework.cloud:spring-cloud-starter-hystrix' compile 'org.springframework.cloud:spring-cloud-starter-hystrix-dashboard' } Spring boot 1.x.x -
481 Rent Service Payment Service No TraceId No SpanId TraceId
= X SpanId = A TraceId = X SpanId = B TraceId = X SpanId = C -
482 Rent Service Payment Service Blockchain Service No TraceId No
SpanId TraceId = X SpanId = A TraceId = X SpanId = B TraceId = X SpanId = C TraceId = X SpanId = D TraceId = X SpanId = D TraceId = X SpanId = F -
483 Rent Service Payment Service Security Service Blockchain Service No
TraceId No SpanId TraceId = X SpanId = A TraceId = X SpanId = B TraceId = X SpanId = C TraceId = X SpanId = D TraceId = X SpanId = D TraceId = X SpanId = E TraceId = X SpanId = E TraceId = X SpanId = F TraceId = X SpanId = G -
484 Rent Service Payment Service Security Service Blockchain Service No
TraceId No SpanId TraceId = X SpanId = A TraceId = X SpanId = B TraceId = X SpanId = B TraceId = X SpanId = C TraceId = X SpanId = C TraceId = X SpanId = D TraceId = X SpanId = D TraceId = X SpanId = E TraceId = X SpanId = E TraceId = X SpanId = F TraceId = X SpanId = G -
485 Rent Service Payment Service Security Service Blockchain Service TraceId
= X SpanId = A No TraceId No SpanId TraceId = X SpanId = A TraceId = X SpanId = A TraceId = X SpanId = B TraceId = X SpanId = B TraceId = X SpanId = C TraceId = X SpanId = C TraceId = X SpanId = D TraceId = X SpanId = D TraceId = X SpanId = E TraceId = X SpanId = E TraceId = X SpanId = F TraceId = X SpanId = G -
489 Rent Service Payment Service SpanId = B Client Send
TraceId = X SpanId = A -
490 Rent Service Payment Service SpanId = B Client Send
SpanId = B Server Received TraceId = X SpanId = A TraceId = X SpanId = C -
491 Rent Service Payment Service SpanId = B Client Send
SpanId = B Server Received SpanId = B Server Send TraceId = X SpanId = A TraceId = X SpanId = C -
492 Rent Service Payment Service SpanId = B Client Send
SpanId = B Server Received SpanId = B Client Received SpanId = B Server Send TraceId = X SpanId = A TraceId = X SpanId = C -
Not smart = This is main documentation This document describes
how to be the most fundamental and important document in the world of documents ... COPY-PASTE documentation from another document ... 494 -
Not so smart = This is main documentation This document
describes how to be the most fundamental and important document in the world of documents include::https://raw.github.com/asciidoctor/asciidoctor/master/Gemfile[] include::../other.adoc[] include::/home/tolkv/git/docs-0/superdoc.adoc[] 495 -
Really smart = This is main documentation This document describes
how to be the most fundamental and important document in the world of documents include::https://raw.github.com/asciidoctor/asciidoctor/master/Gemfile[] include::gradle://gradle-advanced:service-with-deps:1.0/deps.adoc[] include::gradle://:service/doc.adoc[] 496 -
Payment Service[jar,doc] Insurance Service [jar,doc] One Point of View [UberDoc.zip]
Rent Service[jar,doc] Other Service [jar,doc] Агрегация информации 497 -
Парадокс централизации Чтобы эффективно разрабатывать распределённые приложения, нам нужны очень
хорошие централизованные библиотеки и инструменты Например: логирование, health-checking, метрики, обработка типовых ошибок, автодокументирование 498 -
Парадокс централизации Чтобы эффективно разрабатывать распределённые приложения, нам нужны очень
хорошие централизованные библиотеки и инструменты Но: не выносите бизнес-логику или доменные объекты! Не размывайте бизнес-контекст вашего API 499 -
Reactive manifesto Отзывчивость Эластичность Стабильность Асинхронное адресное общение * *
у сообщения есть адресат * топология системы динамическая * компоненты слабо связаны -
Reactive manifesto Отзывчивость Эластичность Стабильность Асинхронное адресное общение * *
у сообщения есть адресат * топология системы динамическая * компоненты слабо связаны -
Reactive manifesto Отзывчивость Эластичность Стабильность Асинхронное адресное общение * *
у сообщения есть адресат * топология системы динамическая * компоненты слабо связаны -
Reactive manifesto Отзывчивость Эластичность Стабильность Асинхронное адресное общение * *
у сообщения есть адресат * топология системы динамическая * компоненты слабо связаны -
Reactive manifesto Отзывчивость Эластичность Стабильность Асинхронное адресное общение * *
у сообщения есть адресат * топология системы динамическая * компоненты слабо связаны -
514 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service -
515 Хочу бегемота! Rent Service Payment Service Security Service Blockchain
Service Insurance Service Sync Sync Sync -
Netty. Асинхронный вход Client Client Client Async threads Event loop
Single thread Selector Delegate -
Reactor IPC Netty WebFlux Dispatcher Handler Controllers Channel Operations Publisher
Publisher Spring WebFlux -
Reactor IPC Netty WebFlux Dispatcher Handler Controllers Channel Operations Publisher
Publisher Spring WebFlux -
Config Client • Пробуем сделать examinator реактивным • Подключаем spring-boot-starter-webflux
• Возвращаем из контроллера Mono<Exam> • Заменяем RestTemplate на WebClient • Выстраиваем стрим от клиента до контроллера -
Gradle apply plugin: "com.google.protobuf" protobuf { protoc { artifact =
'com.google.protobuf:protoc' } generatedFilesBaseDir = "$projectDir/generated" plugins { grpc { artifact = 'io.grpc:protoc-gen-grpc-java' } reactor { artifact = "com.salesforce.servicelibs:reactor-grpc:0.9.0:jdk8@jar" } } generateProtoTasks { ofSourceSet('main')*.plugins { grpc { } reactor { } } -
reactor { artifact = "com.salesforce.servicelibs:reactor-grpc:0.9.0:jdk8@jar" } } generateProtoTasks { ofSourceSet('main')*.plugins
{ grpc { } reactor { } } } } clean { delete protobuf.generatedFilesBaseDir } idea { module { generatedSourceDirs += file("${protobuf.generatedFilesBaseDir}/main/java") generatedSourceDirs += file("${protobuf.generatedFilesBaseDir}/main/reactor") generatedSourceDirs += file("${protobuf.generatedFilesBaseDir}/main/grpc") generatedSourceDirs += file("${protobuf.generatedFilesBaseDir}/main/rsocketRpc") } } dependencies { compile 'com.google.protobuf:protobuf-java' Gradle -
ofSourceSet('main')*.plugins { grpc { } reactor { } } }
} clean { delete protobuf.generatedFilesBaseDir } idea { module { generatedSourceDirs += file("${protobuf.generatedFilesBaseDir}/main/java") generatedSourceDirs += file("${protobuf.generatedFilesBaseDir}/main/reactor") generatedSourceDirs += file("${protobuf.generatedFilesBaseDir}/main/grpc") generatedSourceDirs += file("${protobuf.generatedFilesBaseDir}/main/rsocketRpc") } } dependencies { compile 'com.google.protobuf:protobuf-java' compile 'io.grpc:grpc-stub' compile 'io.grpc:grpc-protobuf' compile 'com.salesforce.servicelibs:reactor-grpc-stub' } Gradle -
*.proto import "google/api/annotations.proto"; package my.error_service; service Errors { rpc GetErrorClass
(GetErrorClassRequest) returns (GetErrorClassResponse) { option (google.api.http) = { post: "/errorclass" body: "*" }; } } message GetErrorClassRequest { string error_id = 1; } message GetErrorClassResponse { string error_class = 1; }