Mall spike system to achieve (a) to build the project framework

springboot quick start

https://projects.spring.io/spring-boot/
https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/htmlsingle/

1. Modify pom, add dependencies

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

2. Create a directory structure, controller, service, dao

Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description

3. Create MainApplication DemoController

@SpringBootApplication
public class MainApplication {
	 public static void main(String[] args) throws Exception {
	        SpringApplication.run(MainApplication.class, args);
	    }
}

4. Create Result

result for results stored call

Contains the return status code Code, data, and information data msg

package com.pro.miaosha.result;

public class Result<T> {
	
	private int code;
	private String msg;
	private T data;
	
	/**
	 *  成功时候的调用
	 * */
	public static  <T> Result<T> success(T data){
		return new Result<T>(data);
	}
	
	/**
	 *  失败时候的调用
	 * */
	public static  <T> Result<T> error(CodeMsg codeMsg){
		return new Result<T>(codeMsg);
	}
	
	private Result(T data) {
		this.data = data;
	}
	
	private Result(int code, String msg) {
		this.code = code;
		this.msg = msg;
	}
	
	private Result(CodeMsg codeMsg) {
		if(codeMsg != null) {
			this.code = codeMsg.getCode();
			this.msg = codeMsg.getMsg();
		}
	}
	//这里还有setter和getter,篇幅限制先省略
}

5. Create CodeMsg

For storing code and status message

package com.pro.miaosha.result;

public class CodeMsg {
	
	private int code;
	private String msg;
	
	//通用的错误码
	public static CodeMsg SUCCESS = new CodeMsg(0, "success");
	public static CodeMsg SERVER_ERROR = new CodeMsg(500100, "服务端异常");
	public static CodeMsg BIND_ERROR = new CodeMsg(500101, "参数校验异常:%s");
	//登录模块 5002XX
	public static CodeMsg SESSION_ERROR = new CodeMsg(500210, "Session不存在或者已经失效");
	public static CodeMsg PASSWORD_EMPTY = new CodeMsg(500211, "登录密码不能为空");
	public static CodeMsg MOBILE_EMPTY = new CodeMsg(500212, "手机号不能为空");
	public static CodeMsg MOBILE_ERROR = new CodeMsg(500213, "手机号格式错误");
	public static CodeMsg MOBILE_NOT_EXIST = new CodeMsg(500214, "手机号不存在");
	public static CodeMsg PASSWORD_ERROR = new CodeMsg(500215, "密码错误");
	
	//商品模块 5003XX
	
	//订单模块 5004XX
	
	//秒杀模块 5005XX
	
	private CodeMsg( ) {
	}
			
	private CodeMsg( int code,String msg ) {
		this.code = code;
		this.msg = msg;
	}
	
	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	
	public CodeMsg fillArgs(Object... args) {
		int code = this.code;
		String message = String.format(this.msg, args);
		return new CodeMsg(code, message);
	}

	@Override
	public String toString() {
		return "CodeMsg [code=" + code + ", msg=" + msg + "]";
	}	
}

Browse Accesshttp://localhost:8080/demo/hello/api

6. Integrated thymeleaf

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

7. Add the configuration application.properties

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

Note that the space behind can not otherwise be able to find templates

8. The front end of the transfer template / hello.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'hello:'+${name}" ></p>
</body>
</html>

9. Integrated mybatis

Outline:

  • Add dependent
  • application.properties configuration druid
  • The establishment of a database table name + id
  • Add Object called User in the domain (including name and id)
  • Adding an interface called dao in UserDao (@ Mapper. @ Select @Insert)
  • userService has userdao a @autowired, call the UserDao directly getById among getById

http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
add dependencies:

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.3.1</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>1.0.5</version>
</dependency>

Add a data source configuration druid

#mybatis
mybatis.type-aliases-package=com.imooc.miaosha.domain
mybatis.mapperLocations = classpath:com/imooc/miaosha/dao/*.xml
mybatis.configuration.map-underscore-to-camel-case=true
#datasource
spring.datasource.url=jdbc:mysql://10.110.3.62:3333/miaosha?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#druid
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.filters=stat
spring.datasource.maxActive=2
spring.datasource.initialSize=1
spring.datasource.maxWait=60000
spring.datasource.minIdle=1
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=select 'x'
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxOpenPreparedStatements=20

Add config:

public class DruidConfig {
	private String url;
	private String username;
	private String password;
	private String driverClassName;
	private String type;
	private String filters;
	private int maxActive;
	private int initialSize;
	private int minIdle;
	private long maxWait;
	private long timeBetweenEvictionRunsMillis;
	private long minEvictableIdleTimeMillis;
	private String validationQuery;
	private boolean testWhileIdle;
	private boolean testOnBorrow;
	private boolean testOnReturn;
	private boolean poolPreparedStatements;
	private int maxOpenPreparedStatements;
  @Bean
	public DataSource druidDataSource() {
    DruidDataSource datasource = new DruidDataSource();
    datasource.setUrl(url);
    datasource.setUsername(username);
    datasource.setPassword(password);
    datasource.setDriverClassName(driverClassName);
    datasource.setInitialSize(initialSize);
    datasource.setMinIdle(minIdle);
    datasource.setMaxActive(maxActive);
    datasource.setMaxWait(maxWait);
    datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    datasource.setValidationQuery(validationQuery);
    datasource.setTestWhileIdle(testWhileIdle);
    datasource.setTestOnBorrow(testOnBorrow);
    datasource.setTestOnReturn(testOnReturn);
    datasource.setPoolPreparedStatements(poolPreparedStatements);
    datasource.setMaxOpenPreparedStatements(maxOpenPreparedStatements);
    try {
        datasource.setFilters(filters);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return datasource;
	}
}
	@Bean
	public ServletRegistrationBean druidStatServlet() {
		ServletRegistrationBean reg = new ServletRegistrationBean();
		reg.setServlet(new StatViewServlet());
		reg.addUrlMappings("/druid/*");
		reg.addInitParameter("loginUsername", "caAdmin");
		reg.addInitParameter("loginPassword", "caPass123");
		reg.addInitParameter("logSlowSql", "true");
		reg.addInitParameter("slowSqlMillis", "1000");
		return reg;
	}
  • Add mysql-connctor, druid dependent

  • Create a data table User, Service, Dao, Domain

    CREATE TABLE user (
      id int(11) NOT NULL,
      name varchar(24) DEFAULT NULL,
      PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    
  • @Select comment

    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.imooc.miaosha.dao.UserDao">
    </mapper>
    

(1) getById test
(2) test the transaction @Transactional

10. integration redis

  • Install redis
    download the installation file http://redis.io/redis-4.0.2.tar.gz redis

    tar -zvxf redis-4.0.2.tar.gz
    cd redis-4.0.2
    make 
    make install
    src/redis-server & //启动服务器
    src/redis-cli //客户端连接
    util/install_server.sh 安装成系统服务
    chkconfig –-list | grep redis 查看是否开机启动
    
  • Configuration redis.conf

    daemonize yes
    bind 0.0.0.0
    requirepass
    

Add Configuration

And introducing jedis dependent fastjson

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.38</version>
</dependency>

Add Configuration:

#redis
redis.host=10.110.3.62
redis.port=6379
redis.timeout=3
redis.password=123456
redis.poolMaxTotal=10
redis.poolMaxIdle=10
redis.poolMaxWait=3
@ConfigurationProperties(prefix="redis")
@Component
public class RedisConfig {
	private String host;
	private int port;
	private int timeout;//秒
	private String password;
	private int poolMaxTotal;
	private int poolMaxIdle;
	private int poolMaxWait;//秒
}

编写 RedisSerive KeyPrefix BaseKey

package com.pro.miaosha.redis;

public interface KeyPrefix {
	public int expireSeconds();
	public String getPrefix();
}

package com.pro.miaosha.redis;

public abstract class BasePrefix implements KeyPrefix{

	private int expireSeconds;
	private String prefix;
	
	public BasePrefix(String prefix) {
		this(0,prefix);
	}
	
	public BasePrefix(int expireSeconds, String prefix) {
		super();
		this.expireSeconds = expireSeconds;
		this.prefix = prefix;
	}
	public int expireSeconds() {
		return expireSeconds;//默认0代表永不过期
	}

	public String getPrefix() {
		String className = getClass().getSimpleName();
		return className+":"+prefix;	
	}
}
package com.pro.miaosha.redis;

public class UserKey extends BasePrefix{
	
	private UserKey(String prefix) {
		super(prefix);
	}
	
	private UserKey(int expireSeconds,String prefix) {
		super(expireSeconds,prefix);
	}
	
	public static UserKey getById = new UserKey("id");
	public static UserKey getByName = new UserKey("name");
	
}

Published 84 original articles · won praise 9 · views 10000 +

Guess you like

Origin blog.csdn.net/Mercuriooo/article/details/104331179