Java developers face by (a)

Nignx used to doing, forwarding policy?

Static HTTP server, proxy static resources (mainstream static resource server), forward dynamic requests, load balancing, higher efficiency relative to the tomcat server such as Dynamic Resource resolve

Forwarding policy

1. Default Polling

upstream backserver{
    server 192.168.1.1:8080
    server 192.168.1.2:8080
}

2. the specific gravity Weight (when learning to speak when the weighted random random referred to)

upstream backserver {
    server 192.168.1.1:8080 weight=3;
    server 192.168.1.2:8080 weight=7;
}

3.IP_hash assigned by each request access ip hash result, the problem can be solved session login information

upstream backserver {
    ip_hash;
    server 192.168.0.14:88;
    server 192.168.0.15:80;
}

(There are other third party)

4.fair by response time

upstream backserver {
    server server1;
    server server2;
    fair;
}

Press 5.url_hash access url hash result to the allocation request, each directed to the same server url

upstream backserver {
    server squid1:3128;
    server squid2:3128;
    hash $request_uri;
    hash_method crc32;
}

use

  • upstream: Status of each device:
  • down: Indicates the current servertime being does not participate in load
  • weight: The default is 1 weightgreater, the greater the weight load of weight.
  • max_fails: The number of permitted default request failed when a maximum number is exceeded, return proxy_next_upstreammodule defined error
  • fail_timeout: max_failsAfter the defeat, pause time.
  • backup: All other non- backupmachine downor busy, requests backupthe machine. So this machine will be the lightest pressure
proxy_pass http://backserver/; 
upstream backserver{ 
    ip_hash; 
    server 127.0.0.1:9090 down; 
#(down 表示单前的server暂时不参与负载) 
    server 127.0.0.1:8080 weight=2; 
#(weight 默认为1.weight越大,负载的权重就越大) 
    server 127.0.0.1:6060; 
    server 127.0.0.1:7070 backup; 
#(其它所有的非backup机器down或者忙的时候,请求backup机器) 
} 


worker_processes  4;
events {
# 最大并发数
worker_connections  1024;
}
http{
    # 待选服务器列表
    upstream myproject{
        # ip_hash指令,将同一用户引入同一服务器。
        ip_hash;
        server 125.219.42.4 fail_timeout=60s;
        # fail_timeout:max_fails次失败后,暂停的时间
        server 172.31.2.183;
    }

    server{
        # 监听端口
        listen 80;
        # 根目录下
        location / {
        # 选择哪个服务器列表
            proxy_pass http://myproject;
        }
        
    }
}

ActiveMQ usage scenarios?

Introduced primarily to the message queue, asynchronously, decoupling, clipping. It can be understood as the communication (between producers and consumers) between two applications.

After the request returns immediately sent to the queue, the Fischer process by acquiring data from the message queue, asynchronously written to the database, the delay can be effectively improved

Where they are needed message mechanism, such as: publish, subscribe, send messages point to point;

Need to use local queues, such as: spike, rush tickets, order processing, and message delivery module. (Front and rear ends velocity inconsistent)

Spring MVC workflow, common notes

Common Annotations

@Controller: This class is a controller identifier

@RequestMapping: to bind a controller method uri

@ResponseBody: The java object into a json, and sent to the client

@RequestBody: client request to turn over the java object json

@RequestParam: when the form and method parameter name parameter inconsistent, to make a name mapping

@PathVarible: uri parameter is used to obtain, the value of such user / 1 of 1

The new api Rest style

@RestController equivalent @ Controller + @ResponseBody

@GetMapping@DeleteMapping@PostMapping@PutMapping

Other notes

@SessionAttribute: What will declare the model data into the session

@CookieValue: get the cookie value

@ModelAttribute: a method return value in the model

@HeaderValue: value acquisition request header

working principle

Request DispatcherServlet-> Returns mapping processor controller -> adapter performs processing controller returns ModelAndView-> render the view -> render the view -> return a response

specific:

1, the user sends a request to the front-end controller DispatcherServlet.

2, DispatcherServlet HandlerMapping call processor receives a request mapper.

3, the processor mappers find specific processor (depending on the configuration xml, notes to find), the object is generated processors and processor interceptors (if there is generated) together return to DispatcherServlet.

4, DispatcherServlet call HandlerAdapter processor adapter.

5, HandlerAdapter through specific adaptation call processor (Controller, also known as back-end).

6, Controller execute complete return ModelAndView.

7, HandlerAdapter the controller ModelAndView the results back to the DispatcherServlet.

8, DispatcherServlet ModelAndView will pass ViewReslover view resolver.

9, ViewReslover returns parsed particular View.

10, DispatcherServlet render view (model data coming filled view) The View.

11, DispatcherServlet user response.

img

Spring understanding of the IOC and AOP, and used to annotate

IOC

Inversion of Control, the right to create objects handed over to the Spring container to complete, and then injected into the object (DI dependency injection)

Achieved mainly through injection bean post processor BeanPostProcessor interface implementation class

  • Based constructor dependency injection

  • Dependent setting function based on injection

  • Injection dependent on automatic assembly

    Automatic assembly has three modes: byType (type pattern), byName (model name), constructor (the constructor mode)

  • Annotation-based dependency injection

    @Autowired byType, with multiple instances of the specified name @Qulifier, if you want to allow a null value, it is required attribute can be set to false

    @Resource default ByName, you can specify

AOP

Oriented Programming, repeated vertical, lateral extraction

Application: logs, permissions, commissioning, affairs

Aspect,Join Point,Advice(Before,After,After-returning,After-throwing,Around,Pointcut)Introduction,Target Object,AOP Proxy,Wearving

Java is essentially a dynamic proxy and bytecode enhancement CGLIB

JDK dynamic proxy
using interceptors (interceptor must implement InvocationHanlder) plus reflection generates an anonymous agent class that implements the interface,

InvokeHandler to handle the call before the call to a specific method.

CGLiB dynamic proxy
using ASM open source packages, class files proxy object classes loaded in, processed by modifying a subclass bytecode.

CGLIB achieve dynamic proxy must implement MethodInterceptor (method interceptors) Interface

the difference

jdk not only for the class implements the interface for agents.

CGLib achieved by proxy inheritance. So the best way to class or not declared as final, for a final class or method can not be inherited.

select

1) When implementing an interface Bean, Spring will use the JDK dynamic proxy.

2) When Bean does not implement the interface, Spring use CGlib is achieved.

3) can force CGlib (added in the spring arrangement )。

@Aspect
@Component//配置bean
public class WebLogAspect {
    private Logger logger = Logger.getLogger(getClass());

    @Pointcut("execution(public * com.jibny.boot.projects.web.controller..*.*(..))")
    public void webLog() {}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        logger.info("---------------request----------------");
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String name = (String) enu.nextElement();
            logger.info("name:" + name + " - value:" + request.getParameter(name));
        }
    }
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        logger.info("---------------response----------------");
        // 处理完请求,返回内容
        logger.info("RESPONSE : " + ret);
    }
}

Chat Mybatis

1. Read the configuration file, a database containing connection information and map files or Mapper Mapper package path,

2. Create SqlSessionFactory by SqlSessionFactoryBuilder,

3.SqlSessionFactory establish SqlSession (Closing the method), the purpose of the implementation of sql statement

4. Analytical sql sql corresponding dynamic label, and encapsulated into MapperStatement objects, execution returns results executor

Notes binding Sql: @ Select @ Update @ Delete @ Insert

Sql XML Binding

Note that the full class name of the local namespace of the specified class

parameterType query parameters

resultType attribute table corresponding field should be

if-test dynamic Sql

<mapper namespace="top.shmly.mapper.UserMapper">    
    <select id="findUserByIds" parameterType="list" resultType="user">
        <!-- SELECT * FROM user WHERE id in (1,2,3) -->
        SELECT * FROM user
        <where>
            <if test="list != null and list.size > 0">
                <foreach collection="list" item="id"                        open="id in(" close=")" separator=",">
                    ${id}
                </foreach>
            </if>
        </where>
    </select>
</mapper>

resultMap properties and column names of the database table is not at the same time you can specify fields, lazy loading can be achieved (no return immediately associated with query results, check orders, do not necessarily need to go back in time product information corresponding to the order), to achieve too much trouble for multi-table model nested models (multi-table may be encapsulated with the resultType VO)

assocication can specify the object of joint

<resultMap id="userResultMap" type="user">
    <id property="id" column="id_"></id>
    <result property="username" column="username_"></result>
    <result property="sex" column="sex_"></result>
    <result property="birthday" column="birthday_"></result>
    <result property="address" column="address_"></result>
</resultMap>
<select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">
    SELECT
     id id_,
     username username_,
     sex sex_,
     birthday birthday_,
     address address_
    FROM user WHERE id = #{id}
</select>

mapper reverse engineering and inheritance tk.mapper

Reverse generated by mybatis-generator automatically generates single-table queries of the database table model, modelExample, mapper interfaces, mapper.xml, conditional screened by Example.Criteria.

Cons: database table field changes, you must modify the configuration file, batch operations to be rewritten, does not support paging, poor portability

Mapper general, dependent on the introduction of inheritance Mapper interface, a universal Mapper already written some common built-in interface, global Example class, the property plus a (persistent) annotations supports batch operations such as paging and

@Id mark the primary key, @ Column (name = "true name"), @ Tranisent ignored field

Spring Boot autowiring

@SpringBootApplication combination comment

  • @SpringBootConfiguration
  • @EnableAutoConfiguration
  • @ComponentScan

By opening the automatic assembly wherein @EnableAutoConfiguration

@EnableAutoConfiguration turn automatic assembly -> @ Import ({EnableAutoConfigurationImportSelector}) import configuration -> SpringFactoriesLoader.loadFactoryNames scanning META-INF / spring.factories File -> class @Conditional conditions at AutoConfiguration dependencies annotations

@ConditionalOnBean
@ConditionalOnClass
@ConditionalOnMissingBean
......

mysql index

Index search and retrieval speed can be optimized to avoid full table scan, index creation condition usually after the where clause field

mysql using B + tree index data structure, similar variants balanced binary tree, non-leaf nodes stored address pointers to child nodes, the leaf nodes only stored data, non-decreasing order from left to right.

Index engine is implemented in the storage layer, rather than implemented in the server layer, different storage engines having different index type and implementation. B + Tree index InnoDB divided main index and a secondary index.

Primary index leaf node data field records the complete data record, which is called indexing clustered indexes. Because there is no line data stored in two different places, so a table can have only one clustered index.

leaf node data field of secondary indexes primary key value is recorded, and therefore when a secondary index to find, it is necessary to find the primary key, and then to lookup the primary index.

The index using the principles and considerations
  • Creating indexes and index maintenance takes time, this time with the increase in the amount of data increases.
  • In addition to the data table space outside the accounting data, each index also account for a certain physical space. If you want to build a clustered index, the space needs will be greater.
  • When the data in the table to add, delete and modify, the index should be dynamically maintained, thus reducing the speed of data maintenance.

Indexed follow the principle:

  • Index on a column often need to search, you can speed up your search.
  • Created on a primary key index of the column, the column is forced to uniqueness, and the organization structure of the data arrangement table.
  • Created on columns that are frequently joined tables using an index, these are some of the major foreign key columns, you can speed up table connection.
  • Create an index on columns that are frequently required in accordance with the scope of the search, because the index has been sorted, so its specified range is continuous.
  • Often need to create an index on the sort columns, because the index has been sorted, so you can use the index to sort the query, the query speed up the sorting.
  • Creating indexes on columns often use the WHERE clause to speed up the determination speed conditions.

The overall answer is generally missed a lot, a lot of preparation (Java foundation collections, multi-threading, transactions, and lock) did not speak

Guess you like

Origin www.cnblogs.com/binjz/p/12501381.html