Tuesday, 27 October 2020

Spring

  • To build enterprise java applications
  • simpler & light weight
  • Spring 4 Key Features
    • Inversion of Control
    • Dependency injection
    • Spring AOP
    • Spring MVC
  • Spring 5 new features
    • Spring WebFlux

Spring Framework

  • Goals
    • Light weight java development with pojos
    • Dependency injection for loose coupling
    • Declarative programming with AOP(Aspect Oriented Programming)
    • Minimize boiler plate java code
  • Core Container
    • Beans
    • Core
    • SpEL
    • Context
  • Infrastructure
    • AOP
    • Aspects
    • Instrumentation
    • Messaging
  • Data access Layer
    • JDBC
    • ORM -> Object relation mapping
    • Transactions
      • OXM
      • JMS
  • Web Layer
    • Servlet
    • Websocket
    • web
    • portlet
  • Test layer
    • Unit
    • integration
    • Mock
Spring Projects
  •     Only use what you need
    • Spring Cloud, Spring Data
    • Spring Batch, Spring Security
    • Spring for Android, Spring for web flow
    • Spring for Webservices, Spring for LDAP
    • Spring Boot, Spring Social

Dev Env setup

  • Tomcat8.5 + Eclipse 
  • Create Project
  • Create a new folder lib in the project
  • Download spring-framework-5.0.2-Release-dist.zip
  • Add jar to the lib folder in the project
  • Project properties -> java build path -> libraries -> classpath -> add jars -> select jars from lib folder
  • Now referenced libraries should show the jars added
Spring Inversion of Control
  • Design process of externalizing of construction and management of Objects
Spring Container
  • Primary functions 
    • Create and manage Objects(Inversion of control) - Object Factory
    • Inject Objects dependencies (Dependency management) -
  • Configuration
    • XML configuration (legacy)
    • Java annotations(modern)
    • Java source code(modern)
Spring development process
  • Configure spring beans in config file
    • applicationContext.xml -> define beans with bean ID & fully qualified class name
  • Create Spring container
    • This is generally known as ApplicationContext
    • ClassPathXmlApplicationContext context = new  ClassPathXmlApplicationContext("applicationContext.xml");
  • Retrieve beans from container
    • Coach coach = context.getBean("myCoach",MyCoach.class);
Spring Dependency Injection
  • Dependency is same as helper objects
  • Injection Types
    • Constructor Injection
    • Setter Injection
  • Development process - constructor injection
    • Create Dependency Interface & class that implements it
    • Create Constructor in your class with parameter as Dependency Interface type
    • Spring bean container/context
      • Define Dendency bean
      • Define regular bean and inject Dependency-bean as Constructor-arg
  • Development process - setter injection
Bean Scopes
  • Singleton
    • for stateless beans
  • prototype
    • new object for each request
    • for statefull bean
  • request
    •  
  • session
  • global-session

Configuration with Annotations(XML Component scan)

  • XML configuration can be too verbose for big projects
  • Scanning for component classes
    • Spring scans classes for special annotations
    • They automatically register them in container
  • Development process
    • Enable component scanning in spring config file
      • provide the base package for  component scan in config file
    • add @Component annotation to java class
    • retrieve bean  from spring container using context.getBean(<beanID>,Bean.class)
  • autoWiring
    • Spring looks for class that matches the property(class/interface) and injects it automatically.
    • Injection types
      • Construction
        • @Autowired on top of constructor
      • Setter
      • Field

Java Configuration

  • Development process
    • Annotate java class with @ComponentScan & @Configuration

Spring MVC

  • webpages to layout UI components
  • Spring beans(Controller, services)
  • Spring configuration(xm, annotations or java)
  • Controller
    • @Controller which inherits from Component
      • @RequestMapping -> controller method
  • Model
    • It is container of application data
  • Form Tags

AOP(Aspect Oriented Programming).

  • It is module/code for cross cutting concenrs
  • Technique based on concept of Aspect
  • Aspect encapsulates cross-cutting logic
  • It can be reused at multiple locations
  • same aspect can be applied based on configuration
  • Benefits
    • Code lies in one class and not scattered
    • code reuse and easy to change
    • Business code is clean
    • Configurable
  • Use cases
    • Logging, security, transactions
    • audit logging
    • exception handling
    • API Management
      • analytics/metrics
  • Disadvantages
    • Too many aspects - hard to follow app flow
    • minor perf cost for aspect execution
  • Terminology
    • Aspect - It is module/code for cross cutting concerns
    • Advice -What action is taken and when it should be applied
      • BeforeAdvice..........
    • Joint Point - When to apply code during program execution
    • Pointcut-
    • Weaving 
      • Connecting aspects to target objects to create an advised object
      • types of weaving
        • Compile time, load time or run time
  • Frameworks
    • SpringAOP, AspectJ
    • SpringAOP advantages
      • Simpler than SpectJ
      • users Proxy pattern
      • can migrate to AspectJ when using @Aspect annotation
    • Spring AOP disadvantages
      • supports only method-level joint points
      • can apply aspects to beans created by Spring app context
      • minor perf impact due to runtime aspect

Spring Security

  • HTTP Basic Authentication
    • builtin dialog from browser
  • Default login form
    • Spring provides default form
  • Custom login form

Spring REST

  • JSON
    • Databinding 
      • process of converting json data into java pojo and vice versa
      • spring uses jackson project behind the scene
      • Json data sent to spring controller will be automatically converted to pojo
      • java object returned from rest  controller will be converted to JSON
    • HTTP Request Message
      • Request line
      • Header variables
      • Message Body
    • REST Controller
    • Exception Handler
      • ResponseEntity is a wrapper on HTTP response object

Spring JDBC

  • Spring simplifies the way we use java technologies
  • JDBC 
    • Developers write lot of code which is repeated across classes in application
      Connection, Statement, setParameters,
    • handle checked exceptions
  • SpringJDBC
    • Simplifies jdbc by creating JDBCTemplate
    • it is combination of JDBC + Template design pattern
    • Template carries common or boiler plate code and reduces amount of developers work
    • JDBCTemplate depends on javax.sql.DataSource
  • Steps to use JDBCTemplate
    • config.xml
      • create/configure bean dataSource for class DriverManagerDataSource providing driverClassName, url, user, pwd
      • create/configure bean jdbcTemplate for class JDBCTemplate passing dataSource from above step
      • jdbcTemplat.update(sql, <params to sql>);
    • Query
      • RowMapper
        • Interace in Spring framework which needs to be implemented
        • It maps resultset into Object of class that we create
        • mapRow() to be implemented
        •  
    • config.xml
Spring Boot
  • Challenges addressed
    • what maven arche type to be used
    • what maven dependencies to be used
    • configuration file
    • what server to be used
  • Spring boot 
    • easier to get started with Spring development
    • minimize amount of manual configuration
    • auto config based on props file and jar class path
    • embedded server
    • Overall- It is self-contained unit
  • Spring initializer
    • create starter project, select dependencies,
      • https://start.spring.io/
    •  Creates Maven/gradle project
    • Import project into IDE
  • One can run the app from command line and IDE
    • java -jar <jar name>
  • Source code generated by spring boot initializer
    • import org.springframework.boot.autoconfigure.SpringBootApplication
      @SpringBootApplication  -> This is composed of other annotations
      • The annotation composed of @EnableAutoConfiguration
        @ComponentScan
        @Configuration
    • SpringApplication.run
      • Creates application context, register all beans
      • starts embedded tomcat server
    • application.properties for Custom properties
      • Change default port
        server.port=8181
      • Properties defined here can be referenced in using
        @Value("${<property name>}")
        private String var1
  • Spring boot dev tools
    • Automatically restart application when code is changed
    • simply add dependency spring-boot-devtools
  • Spring boot Actuator
    • Exposes end points to monitor application
    • Easily get dev ops functionality out of box
    • simply add dependency spring-boot-starter-actuator
      • ../health
        ../info
  • Run from Command line
    • java -jar <application.jar>
    • mvnw:spring-boot:run

SpringBoot - Datasource configuration for Hibernate 

  • application.properties
    • spring.datasource.url
    • spring.datasource.username
    • spring.datasource.password
  • Spring boot will automatically create beans for DataSource and EntityManager
  •  

Monday, 26 October 2020

Prometheus

  • The Prometheus monitoring system and time series database
  • To monitor workloads
  • open source monitoring solution
  • Scape data/metrics using http end points
  • All data is stored as TimeSeries
    • Every time series is identified by metric name and a set of key-value pairs, called labels

  • Types of metrics
    • Counter
      • Value that only goes up
    • Gauge
      • Numeric value that can go up and down(like cpu load)
    • Histogram
      • Sample observations(request duration, response sizes)
    • Summary
  • PromQL
    • Provides builtin operators and functions
    • expressions over time-series vectors
  • Querying metrics
    • Instant Vector
        • single sample for each time series - all sharing the same time stamp
        • eg: node_cpu_seconds_total
    • Range Vector
      • range of data points over time for each time series
      • eg: node_cpu_seconds_total[5min]
    • Scalar
      • Simple numeric floating point value
  • Service discovery
    • Automatic detection of devices and services offered by these devices on a computer network
  • Exporters
    • Export third party metrics  to Prometheus metrics

Alerting

  • Alerting rules
    • Rules live in Prometheus server config
    •  
  • Alert manager