Java

1.1tomcat

1.2JVM 1.3Mysql

2.1SpringCloud

2.2SpringBoot 2.3Dubbo

4.1Spring 4.2SpringMVC 4.3MyBatis

5.1 5.2 5.3

ๅग़ ᩒრ

1.1tomcat 1tomcat 1. JVM -Xms JVM - Xmx JVM 80% catalina.bat JAVA_OPTS='-Xms256m- Xmx512m' 256MB512MB 2.DNS webIP IPDNS IP DNS DNS server.xml enableLookups

Tomcat4

Tomcat5

3. Con nector Tomcat Java CPU

Tomcat4 minProcessors maxProcessors minProcessors 51 5 maxProcessors maxProcessors web server Windows2000Linux1000

Tomcat5 maxThreads Tomcat Tomcat acceptCount connnection Timeout 0 30000 minSpareThreadsTomcat maxSpareThreads Tomcat socket

web

2comcat tomcat server.xml minProcessors 10 maxProcessors 75 acceptCount maxProcessors 100 enableLookups truefalse false connectionTimeout 0 30000 maxProcessorsacceptCount web server Windows2000Linux1000tomcat5

3tomcat java.lang.OutOfMemoryError:Java heap space JAVA

1 Heap size TOMCAT_HOME/bin/catalina.sh setJAVA_OPTS=-Xms32m-Xmx512m

2 java-Xms32m-Xmx800m className JAVAclassName Eclispe ->run-arguments VM arguments -Xms32m- Xmx800m Eclilpse VMarguments -Xms32m-Xmx800m

java.lang.OutOfMemoryError:PermGen space PermGen space Permanent Generation space , , JVMClassMeta,ClassLoader PermGen space ,(Instance)Heap , GC(Garbage Collection) PermGen space CLASS, PermGen space ,webJSP preco mpile WEB APP jar, jvm(4M) MaxPermSize TOMCAT_HOME/bin/catalina.sh “echo"Using CATALINA_BASE:$CATALINA_BASE"” JAVA_OPTS="-server-XX:PermSize=64M-XX:MaxPermSize=128m jar tomcat/shared/lib jar

java.lang.OutOfMemoryError:Java heap space Heap size JVMjavaJVM .JVM Heap size (-Xms) 1/64 (-Xmx) 1/4JVM -Xmn-Xms-Xmx Heap size Young Generation TenuredGeneraion JVM98GC Heap size 2 Heap Size 80 - Xms -Xmx -Xmn 1/4 -Xmx Heap size TOMCAT_HOME/bin/catalina.sh “echo"Using CATALINA_BASE:$CATALINA_BASE"” JAVA_OPTS="-server-Xms800m-Xmx800m-XX:MaxNewSize=256m"

1G java jvm JAVA_OPTS="-server-Xms800m-Xmx800m-XX:PermSize=64M- XX:MaxNewSize=256m-XX:MaxPermSize=128m- Djava.awt.headless=true" webtomcat myeclipsetomcattomcat TOMCAT_HOME/bin/catalina.bat set JAVA_OPTS=-server-Xms2048m-Xmx4096m-XX:PermSize=512M- XX:MaxPermSize=1024M-Duser.timezone=GMT+08 set JAVA_OPTS=-Xmx1024M-Xms512M-XX:MaxPermSize=256m myeclipse Myeclipse->preferences->myeclipse->servers->tomcat- >tomcat×.×->JDK Optional Java VM arguments - Xmx1024M-Xms512M-XX:MaxPermSize=256m myeclipseTomcat "ava.lang.OutOfMemoryError:Java heap space" Myeclipse->preferences->myeclipse>servers->tomcat- >tomcat×.×->JDK Optional Java VM arguments -Xmx1024M-Xms512M- XX:MaxPermSize=256m

4tomcat {tomcat_home}/conf/web.xml listingsfalse

listings false listings false

5Tomcat tomcat

tomcat conf server.xml

Context web webapps conf Catalina localhost xml xml

3 path URL XML 23

: tomcat tomcat war

6Tomcat Tomcat web :

• web.xml jsp Servlet tomcat jvm

• CPU

• CPU

• -Xmx-Xms-XX:MaxPermSize full GC

• Nginxcssjs tomcat gziptomcat Nginx

gzip 300kbkb

• tomcatNginx tomcatsession nginx+tomcat+web

• tomcat tomcat7conf/server.xml dns

1.2JVM 1Java Java 7

1 .

• Class

2 . Class .:

• Class .

• :

• •

3 . Java public static int value=123;//value0 123 4 .

5 . java

6.

7.

2java • • static • . class final • RAM • new Java , •

1.Java Perm Gen space ? JVM JVM

3JVMClass Java Class JVM JVM .class Java ClassLoader

new JVM class.forName() JVM

JVM Java .class

Java JVM

• class • 3 • class • • •

4GC ? GC? GC (GabageCollection) Java GC Java

5 Java Java JVM

6 ?( GC ) : 1 . “”, .

A B B A AB

2 . () : GC Roots GC Roots Java GC Roots : • • • • JNI

GC Root .

GC Root finalize() finalize() finalize() F-Queue Finalize() finalize() F-Queue GC F-Queue ” ”

7 2 Java C++ Java Java “”""

8?? ? GC GC GC (heap) ” ”” ” GC “ ”GC System.gc() GC Java GC

9Java Java Java GC : import java.io.IOException; public class GarbageTest { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub try { gcTest(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("has exited gcTest!"); System.in.read(); System.in.read(); System.out.println("out begin gc!"); for(int i=0;i<100;i++) { System.gc(); System.in.read(); System.in.read(); } } private static void gcTest() throws IOException { System.in.read(); System.in.read(); Person p1 = new Person(); System.in.read(); System.in.read(); Person p2 = new Person(); p1.setMate(p2); p2.setMate(p1); System.out.println("before exit gctest!"); System.in.read(); System.in.read(); System.gc(); System.out.println("exit gctest!"); } private static class Person { byte[] data = new byte[20000000]; Person mate = null; public void setMate(Person other) { mate = other; } } } Java : Java java ( map )

Java

( null ):

public class Stack { private Object[] elements=new Object[10]; private int size = 0 ; public void push(Object e){ ensureCapacity(); elements[size++] = e; } public Object pop(){ if( size == 0) throw new EmptyStackException(); return element s[--size]; } private void ensureCapacity(){ if(elements.length == size){ Object[] oldElements = elements; elements = new Object[2 * elements.length+1]; System.arraycopy (oldElements,0, elements, 0, size); } } }

10 : K G public class Bad{ public static Stack s=Stack(); static{ s.push(new Object()); s.pop(); // s.push(new Object()); // } }

static Stack 100 100 Stack 100 !

: HashSet HashSet contains HashSet HashSet

10

Person p=new Person(“”);

11System.gc() Runtime.gc() ? JVM JVM

12finalize() ? (finalization) ? (garbage colector) finalize() Java filalize() finalize() ? Java JNI(Java Native Interface) non-Java (C C++) finalize()

13 null ?

14(DGC)?? DGC RMI DGC RMI DGC

15(serial)(throughput) ? ( 100M )

16 Java ?

17 Java Minor GC Major GC • Eden • •

Eden Minor GC Minor GC Eden Gc ; Full GC/Major GC GC Minor GC Full GC Minor GC

18JVM ? (Full GC) : Java 8 native

19Java ? - : : 1. ; 2. GC :

1:1 8:1:1 Eden Survior Eden Eden Eden Survivor (java )

- : - ;

:

20? : • (BootstrapClassLoader)Java Java • (extensions class loader): Java Java Java • (system class loader): Java (CLASSPATH) Java Java ClassLoader.getSystemClassLoader() • java.lang.ClassLoader

21?

3Mysql

1SpringCloud 1 Spring Cloud? Spring cloud Spring Boot Spring Spring cloud Task

2 Spring Cloud ? Spring Boot • - • - • - • -- • - • -Devops

3?Spring Cloud ? Eureka Eureka Eureka

4?

5 Hystrix?? Hystrix

​ 9 1000. hystrix Hystrix Fallback employee-consumer employee-consumer

​ employee-producer Hystrix

6 Hystrix ?? employee-consumer Hystrix ​ firstPage method() Hystrix firtsPage

7 Netflix Feign?? Feign RetrofitJAXRS-2.0 WebSocket java Feign http employee-consumer employee- producer REST REST • • URL • REST

1. @Controller 2. public class ConsumerControllerClient { 3. 4. @Autowired 5. private LoadBalancerClient loadBalancer; 6. 7. public void getEmployee() throws RestClientException, IOExc eption { 8. 9. ServiceInstance serviceInstance=loadBalancer.choose("employ ee-producer"); 10. 11. System.out.println(serviceInstance.getUri()); 12. 13. String baseUrl=serviceInstance.getUri().toString(); 14. 15. baseUrl=baseUrl+"/employee"; 16. 17. RestTemplate restTemplate = new RestTemplate(); 18. ResponseEntity response=null; 19. try{ 20. response=restTemplate.exchange(baseUrl, 21. HttpMethod.GET, getHeaders(),String.class); 22. }catch (Exception ex) 23. { 24. System.out.println(ex); 25. } 26. System.out.println(response.getBody()); 27. }

NullPointer Netflix Feign Netflix Ribbon Feign

8 Spring Cloud Bus?? : Spring Cloud Config Spring Cloud Config GIT Employee Config Module Eureka ​ GIT Eureka Eureka / url Employee Producer1 8080 http:// localhost:8080 / refresh Employee Producer2 http:// localhost:8081 / refresh Spring Cloud Bus ​ Spring Cloud Bus Employee Producer1 / /

2SpringBoot 1 Spring Boot? spring https://spring.io/projects Spring Spring Maven spring spring Spring Boot Spring Boot spring spring Spring Boot Spring

2Spring Boot ? Spring Boot : JavaConfig XML Maven Web Tomcat Glassfish web.xml @ Configuration @Bean Spring @Autowired bean Spring :- Dspring.profiles.active = {enviornment}Spring (application{environment} .properties)

3 JavaConfig? Spring JavaConfigSpringSpring IoC Java XML JavaConfig : JavaConfig Java @Bean XML XML Java JavaConfig Java XML Spring JavaConfig JavaConfig XML JavaConfig Spring Java 5.0 bean

4 Spring Boot ? DEV tomcat Spring Boot (DevTools) Java Spring Boot Spring Boot DevTools H2 org.springframework.boot spring-boot-devtools true

5Spring Boot ? Spring boot actuatorspringSpring boot HTTP URL REST

6 Spring Boot Actuator ? HTTP ACTUATOR HttpServletRequest.isUserInRole management.security.enabled = false

7 Spring Boot ? Spring Boot application.properties server.port = 8090

8 YAML? YAML YAML YAML

9 Spring Boot ? Spring Boot spring-boot-starter-security WebSecurityConfigurerAdapter

10 Spring Boot ActiveMQ? Spring Boot ActiveMQ spring-boot-starter-activemq

11 Spring Boot ? Spring Boot Spring Data-JPA org.springframework.data.domain.Pageable

12 Swagger? Spring Boot ? Swagger API Swagger UI Swagger RESTful Web Swagger Swagger

13 Spring Profiles? Spring Profiles (devtestprod ) bean bean PRODUCTION bean Swagger QA Spring Boot

14 Spring Batch? Spring Boot Batch /

15 FreeMarker ? FreeMarker Java MVC Freemarker html freemarker

16 Spring Boot ? SpringControllerAdvice ControlerAdvice 17 starter maven ? spring-boot-starter-activemq spring-boot-starter-security spring-boot-starter-web

18 CSRF ? CSRF Web CSRF

19 WebSockets? WebSocket TCP WebSocket - WebSocket WebSocket - TCP -HTTP Light - http WebSocket

20 AOP? (AOP)

21 Apache Kafka? Apache Kafka - - Apache Kafka

22 Spring Boot ? Spring Boot ()() 50 50

3Dubbo 1Dubbo zookeeper ? dubbo zk ; ; ; ;

2dubbo ? l Random LoadBalance ( dubbo ) l RoundRobin LoadBalance : l LeastActive LoadBalance l ConsistentHash LoadBalance Hash Hash

160

3 Dubbo Dubbo Token Dubbo

4dubbo l Failsafe Cluster [AppleScript] ? Failover 1. dubbo () Dubbo failover l Failover Cluster() () retries="2"() : cluster="fai lover", failover l Failfast Cluster

dubbo:service cluster="failfast" /> : cluster="failfast" cluster="failover"retries="0" ,retries="0" l Failsafe Cluster

: l Failback Cluster

: l Forking Cluster forks="2"

: l

: AnnotationConfigApplicationContext

public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); MyService myService = ctx.getBean(MyService.class); myService.doStuff(); }

@Configuration :

@Configuration @ComponentScan(basePackages = "com.somnus") public class AppConfig { ... }

com.acme @Component Sring bean web AnnotationConfigWebApplicationContext Spring Servlet ContextLoaderListener Spring MVC DispatcherServlet

contextClass org.springframework.web.context.support.AnnotationConfigWebApp licatio nContext contextConfigLocation com.howtodoinjava.AppConfig contextClass org.springframework.web.context.support.AnnotationConfigWebApp licatio nContext contextConfigLocation com.howtodoinjava.AppConfig

9 Spring? Spring 2.5 XML bean bean XML Spring Spring

Spring : 1. @Required: 2. @Autowired: 3. @Qualifier:@Autowired bean 4. JSR-250 Annotations:Spring JSR-250 @Resource @PostConstruct @PreDestroy

10 Spring Bean ? Spring Bean bean bean bean Spring bean factory spring bean Bean (call back) 1. 2. Spring bean : • InitializingBean DisposableBean • Aware • BeanCustom init()destroy() • @PostConstruct @PreDestroy customInit() customDestroy() bean :

11Spring Bean ? Spring bean 5 : 1. singleton: bean bean bean factory 2. prototype: bean 3. request: bean bean 4. Session: session bean session bean 5. global- session:global-session Portlet Portlet portlet portlet global- session Servlet session

12 Spring inner beans? Spring bean bean bean bean setter “”“” Customer Person Person Customer public class Customer{ private Person person; //Setters and Getters } public class Person{ private String name; private String address; private int age; //Setters and Getters }

bean :

13Spring Beans ? Spring bean bean Spring bean ( Serview DAO ) Spring bean bean ( View Model ) bean “singleton” “prototype”

14 Spring Java Collection? Spring : • : list • : set • : • : :

INDIA Pakistan USA UK INDIA Pakistan USA UK [email protected] [email protected]

15 Spring Bean Java.util.Properties? :

[email protected] [email protected]

”util:” properties propertiesbean setter bean

16 Spring Bean ? Spring bean Spring bean Spring Bean Factory bean bean bean XML bean :

bean @Autowired bean@Autowired Spring

AutowiredAnnotationBeanPostProcessor

@Autowired

@Autowired public EmployeeDAOImpl ( EmployeeManager manager ) { this.manager = manager; } 17? Spring 5 1. no: Spring bean 2. byName: bean bean bean bean 3. byType: bean bean bean bean 4. constructor: byType bean bean 5. autodetect: byType bean byTpe

18? @Autowired AutowiredAnnotationBeanPostProcessor : 1

2 bean AutowiredAnnotationBeanPostProcessor

19@Required ? IoC beanbean bean “dependency-check” bean bean “dependency- check” @Required bean public class EmployeeFactoryBean extends AbstractFactoryBean{ private String designation; public String getDesignation() { return designation; } @Required public void setDesignation(String designation) { this.designation = designation; } //more code here }

RequiredAnnotationBeanPostProcessor Spring @Required bean RequiredAnnotationBeanPostProcesso bean IoC :

@Required BeanInitializationException

20@Autowired ? @Autowired @Autowired @Required bean bean @Autowired Spring setter @Autowired byType @Autowired @Autowired bean

public class TextEditor { private SpellChecker spellChecker; @Autowired public TextEditor(SpellChecker spellChecker){ System.out.println("Inside TextEditor constructor." ); this.spellChecker = spellChecker; } public void spellCheck(){ spellChecker.checkSpelling(); } }

:

21@Qualifier ? @Qualifier bean Qualifier Spring bean Customer person person

public class Customer{ @Autowired private Person person; }

Person

Spring person bean ? :

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionExceptio n: No unique bean of type [com.howtodoinjava.common.Person] is de fined: expected single matching bean but found 2: [personA, pe rsonB]

@Quanlifier Spring bean:

public class Customer{ @Autowired @Qualifier("personA") private Person person; } 22? : 1. int stringlong 2. 3. 4. ABASpring sObjectCurrentlyInCreationException B A Spring

23Spring ? Spring ApplicationContext bean ApplicationContext ApplicationEvent ApplicationContext bean ApplicationListener ApplicationEvent bean public class AllApplicationEventListener implements Applicatio nListener < ApplicationEvent >{ @Override public void onApplicationEvent(ApplicationEvent applicatio nEvent) { //process event } }

Spring 5 : 1. (ContextRefreshedEvent):ApplicationContext ConfigurableApplicationContext refresh() 2. (ContextStartedEvent): ConfigurableApplicationContext Start()/ 3. (ContextStoppedEvent): ConfigurableApplicationContext Stop() 4. (ContextClosedEvent):ApplicationContext Bean 5. (RequestHandledEvent):Webhttp (request) ApplicationEvent public class CustomApplicationEvent extends ApplicationEvent{ public CustomApplicationEvent ( Object source, final String ms g ){ super(source); System.out.println("Created a Custom event"); } }

: public class CustomEventListener implements ApplicationListene r < CustomApplicationEvent >{ @Override public void onApplicationEvent(CustomApplicationEvent applicationEvent) { //handle event } }

applicationContext publishEvent() CustomApplicationEvent customEvent = new CustomApplicationEvent(applicationContext, "Test message"); applicationContext.publishEvent(customEvent);

24FileSystemResource ClassPathResource ? FileSystemResource spring-config.xml ClassPathResource spring ClassPath ClassPathResource ClassPath spring-config.xml src src ClassPathResource FileSystemResource

25Spring ? Spring : o —AOPremoting o —springbean o — .RestTemplate,JmsTemplate,JpaTempl ate o —SpringDispatcherServlet o (ViewHelper)—SpringJSP o —BeanFactory/ApplicationContext o —BeanFactory

26 Spring ? 1. IOC 2. AOP 3. .

27 AOP IOC AOP: Aspect Oriented Program, ();Filter() AOP. AOP , OOP(Object-Oriented Programming, ) . AOP (aspect), .. IOC: Invert Of Control, . DI() . . , . IOC , ,.

28 Spring Bean ? Bean : ()( & )FactoryBean

29IOC Bean : 1. Bean 2. Bean Bean 3. Bean Bean postProcessBeforeInitialization 4. Bean (init-method) 5. Bean Bean postProcessAfterInitialization 6. Bean 7. , Bean (destroy-method)

4.2 SpringMVC 1 SpringMvc? SpringMvc spring MVC

2Spring MVC : 1..,, java . Spring . 2. Servlet API(, Servlet ) 3., JSP 4. 5.

3SpringMVC ? 1. DispatcherServlet 2.DispatcherServlet handlerMapping Controller 3.Controller ModelAndView 4.DispatcherServlet ModelAndView 5.

4SpringMVC ? 1. DispatcherServlet 2.DispatcherServlet HandlerMapping 3.( xml ) () DispatcherServlet 4.DispatcherServlet HandlerAdapter 5.HandlerAdapter (Controller ) 6.Controller ModelAndView 7.HandlerAdapter controller ModelAndView DispatcherServlet 8.DispatcherServlet ModelAndView ViewReslover 9.ViewReslover View 10.DispatcherServlet View ( ) 11.DispatcherServlet

5SpringMvc ,,,? ,,, ,

6 struts2. springMVC struts2 ? 1.springmvc servlet struts2 filter 2.springmvc ( url ) ()struts2 3.Struts OGNL springmvc request ModelAndView ModelAndView reques Jsp jstl 7SpingMvc ,? @Conntroller ,,

8 @RequestMapping ?

9? :@RequestMapping,

10, get ,? @RequestMapping method=RequestMethod.GET

11 Request, Session? request,SpringMvc request

12,? :,

13,, ? ,SpringMvc 14SpringMvc ? :, String, ModelAndView, String

15SpringMVC ? "forward:","forward:user.do? name=method4" "redirect:", "redirect:http://www.baidu.com"

16SpringMvc ? : ModelMap , put ,, el

17SpringMvc ,? ModelAndView

18 ModelMap Session ? @SessionAttributes , session key

19SpringMvc AJAX ? Jackson Java Js Json : 1. Jackson.jar 2. json 3. Ajax Object,List , @ResponseBody

20 AJAX , Object,List , ? @ResponseBody

21SpringMvc ,,, SpringMvc :

22 SpringMvc spring, http disPatherServletspring ModelAndView model map

4.3MyBatis 1 MyBatis? MyBatis SQL

2 MyBatis MyBatis , session , , ,, Serializable (),

3Mybatis ?? 1.Mybatis RowBounds Mybatis 2.: Mybatis sql sql : select * from student

sql : select t.* from (select * from student)t limit 010

4 Mybatis ? 1.Mybatis ParameterHandlerResultSetHandler StatementHandler Executor 4 Mybatis 4 InvocationHandler invoke() 2. Mybatis Interceptor intercept()

5Mybatis sql ? sql? sql ? 1.Mybatis sql Xml sql sql 2.Mybatis 9 sql : trim|where|set|foreach|if|choose|when|otherwise|bind 3. OGNL sql sql sql

6#{}${}? 1. #{} ${} 2.Mybatis #{} sql #{}? PreparedStatement set ; 3.Mybatis ${} ${} 4. #{} SQL

7 Mybatis ORM ? ? ORM Hibernate Mybatis sql ORM

8Mybatis ?? 1.Mybatis association collection association collection Mybatis lazyLoadingEnabled=true|false 2. CGLIB a.getB().getName() invoke() a.getB() null B sql B a.setB(b) a b a.getB().getName()

9MyBatis Hibernate ? 1.Mybatis hibernate ORM MyBatis Sql mybatis XML sql java sql sql sql java 2.Mybatis sql sql mybatis sql 3.Hibernate / () hibernate Hibernate O/R Hibernate

10MyBatis ? 1.MyBatis sql Java XML 2.MyBatis JDBC API Java Bean Java 3. MyBatis sql sql Hibernate orm

11 Mybatis Xml Mybatis ? Mybatis Xml All-In-One Configuration Xml ParameterMap ParameterMapping ResultMap ResultMapping