IDEA下创建Springboot,freemarker,mockserver,Gradle项目

有时候,springboot只是作为一个前置服务,不需要链接数据库,而是去调别人restful接口,然后去展示h5页面。

而且后台接口很多时候是不能在我们前置服务开发之前都开发完的,我们这里就需要一个mock server来模拟后台接口。

这个时候,我们就需要搭建一个Springboot,freemarker,mockserver,Gradle项目了。

话不多说,直接上一套简单框架全部代码。

1、项目结构图

IDEA下创建Springboot,freemarker,mockserver,Gradle项目_第1张图片

2、build.gradle

plugins {
    id 'org.springframework.boot' version '1.5.3.RELEASE'
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'eclipse'


repositories {
    jcenter()
}

jar {
    baseName = 'preserver'
}

sourceCompatibility = 1.7
targetCompatibility = 1.7

compileJava.options.encoding = 'UTF-8'
compileTestJava.options.encoding = 'UTF-8'

task wrapper(type: Wrapper) {
    gradleVersion = '4.1'
}

bootRun {
    addResources = true
}

configurations {
    compile.exclude module: "spring-boot-starter-tomcat"
}

dependencies {
    compile 'org.slf4j:slf4j-api:1.7.21'
    compile 'org.apache.commons:commons-lang3:3.5'
    compile 'com.google.guava:guava:21.0'

    compile 'org.springframework.boot:spring-boot-starter'
    compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'org.springframework.boot:spring-boot-starter-security'
    compile 'org.springframework.boot:spring-boot-starter-undertow'
    compile 'org.springframework.boot:spring-boot-starter-test'
    compile 'org.springframework.boot:spring-boot-starter-aop'
    compile 'org.springframework.boot:spring-boot-starter-logging'
    compile 'org.springframework.boot:spring-boot-starter-freemarker'
    compile 'org.springframework.boot:spring-boot-devtools'

    compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.3'
    compile group: 'com.alibaba', name: 'fastjson', version: '1.2.39'


    testCompile 'junit:junit:4.12'
}

3、application.yaml

spring.profiles.active: local
---
spring:
  profiles: local
  devtools.restart.enabled: true
  output.ansi.enabled: ALWAYS
  freemarker:
    suffix: .html
    settings:
      datetime_format: yyyy-MM-dd HH:mm:ss
      date_format: yyyy-MM-dd
      time_format: HH:mm:ss
      number_format: 0.######
      boolean_format: true,false
      auto_import: "'spring.ftl' as spring"
      whitespace_stripping: true
      default_encoding: UTF-8
      tag_syntax: auto_detect
      url_escaping_charset: UTF-8
      template_update_delay: 3
      locale: zh_CN
      cache_storage: strong:20,soft:250
  resources.chain.strategy:
    content.enabled: true
    fixed.version: 1
  mvc:
    favicon.enabled: false
    static-path-pattern: /**
logging:
  level.root: info
  level.com.smknet.hmls.preserver: info
  path: /home/fuhd/work/workspace/idea/
  file: preserver
servlet:
  container:
    port: 8080
    timeout: 30
net4j:
  url: http://192.168.23.208:9001

---
spring:
  profiles: test
---
spring:
  profiles: pqa

---
spring:
  profiles: prod

4、logback-spring.xml


<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${LOG_PATH}${LOG_FILE}.%d{yyyy-MM-dd}.logFileNamePattern>
            <MaxHistory>30MaxHistory>
        rollingPolicy>
        <encoder>
            <pattern>${FILE_LOG_PATTERN}pattern>
            <charset>UTF-8charset>
        encoder>
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>50MBMaxFileSize>
        triggeringPolicy>
    appender>
    <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${LOG_PATH}${LOG_FILE}_error.%d{yyyy-MM-dd}.logFileNamePattern>
            <MaxHistory>30MaxHistory>
        rollingPolicy>
        <encoder>
            <pattern>${FILE_LOG_PATTERN}pattern>
            <charset>UTF-8charset>
        encoder>
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MBMaxFileSize>
        triggeringPolicy>
    appender>
    <root>
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    root>
    <logger name="com.smknet.hmls.preserver" level="ERROR">
        <appender-ref ref="ERROR_FILE"/>
    logger>
configuration>

5、ProductController

package com.smknet.hmls.preserver.controller;

import com.smknet.hmls.preserver.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 产品控制类
 * Created by dyw on 2017/10/11.
 */
@Controller
@RequestMapping("/product")
public class ProductController {

    private static final Logger logger = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    private UserService userService;

    @RequestMapping("/show")
    public String show(Model model) {
        try {
            String user = userService.getUserName();
            model.addAttribute("user", user);
        } catch (Exception e) {
            //查询抛异常的时候,返回异常页面
            return "test";
        }
        return "test";
    }
}

6、UserServiceImpl

package com.smknet.hmls.preserver.service.impl;

import com.smknet.hmls.preserver.service.UserService;
import com.smknet.hmls.preserver.util.HttpClientUtil;
import org.springframework.stereotype.Service;

/**
 * 用户service实现类
 * Created by dyw on 2017/10/12.
 */
@Service
public class UserServiceImpl implements UserService {

    @Override
    public String getUserName() {
        String userInfo = HttpClientUtil.httpGetRequest("http://localhost:1111/UUS001?accessToken=123456");
        return userInfo;
    }
}

7、HttpClientUtil

package com.smknet.hmls.preserver.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Map;

/**
 * httpclient 工具类
 * Created by dyw on 2017/10/11.
 */
public class HttpClientUtil {
    private static PoolingHttpClientConnectionManager cm;
    //当请求出现异常的时候返回的字符串
    private static String EMPTY_STR = "";
    private static String UTF_8 = "UTF-8";

    private static void init() {
        if (cm == null) {
            cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(50);// 整个连接池最大连接数  
            cm.setDefaultMaxPerRoute(5);// 每路由最大连接数,默认值是2  
        }
    }

    /**
     * 通过连接池获取HttpClient
     *
     * @return
     */
    private static CloseableHttpClient getHttpClient() {
        init();
        return HttpClients.custom().setConnectionManager(cm).build();
    }

    /**
     * http get 方法
     *
     * @param url url链接
     * @return 相应内容String类型
     */
    public static String httpGetRequest(String url) {
        HttpGet httpGet = new HttpGet(url);
        return getResult(httpGet);
    }

    public static String httpGetRequest(String url, Map params) throws URISyntaxException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        ArrayList pairs = covertParams2NVPS(params);
        ub.setParameters(pairs);

        HttpGet httpGet = new HttpGet(ub.build());
        return getResult(httpGet);
    }

    public static String httpGetRequest(String url, Map headers, Map params)
            throws URISyntaxException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        ArrayList pairs = covertParams2NVPS(params);
        ub.setParameters(pairs);

        HttpGet httpGet = new HttpGet(ub.build());
        for (Map.Entry param : headers.entrySet()) {
            httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
        }
        return getResult(httpGet);
    }

    /**
     * http post
     *
     * @param url url
     * @return 相应内容String格式
     */
    public static String httpPostRequest(String url) {
        HttpPost httpPost = new HttpPost(url);
        return getResult(httpPost);
    }

    /**
     * http post
     *
     * @param url  url
     * @param body 消息体
     * @return 响应内容
     */
    public static String httpPostRequest(String url, String body) {
        HttpPost httpPost = new HttpPost(url);
        // 构建消息实体
        StringEntity entity = new StringEntity(body, Charset.forName("UTF-8"));
        entity.setContentEncoding("UTF-8");
        // 发送Json格式的数据请求
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        return getResult(httpPost);
    }

    public static String httpPostRequest(String url, Map params) throws UnsupportedEncodingException {
        HttpPost httpPost = new HttpPost(url);
        ArrayList pairs = covertParams2NVPS(params);
        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
        return getResult(httpPost);
    }

    public static String httpPostRequest(String url, Map headers, Map params)
            throws UnsupportedEncodingException {
        HttpPost httpPost = new HttpPost(url);

        for (Map.Entry param : headers.entrySet()) {
            httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
        }

        ArrayList pairs = covertParams2NVPS(params);
        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));

        return getResult(httpPost);
    }

    private static ArrayList covertParams2NVPS(Map params) {
        ArrayList pairs = new ArrayList();
        for (Map.Entry param : params.entrySet()) {
            pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
        }
        return pairs;
    }

    /**
     * 处理Http请求
     *
     * @param request http请求
     * @return 相应结果
     */
    private static String getResult(HttpRequestBase request) {
        // CloseableHttpClient httpClient = HttpClients.createDefault();  
        CloseableHttpClient httpClient = getHttpClient();
        try {
            CloseableHttpResponse response = httpClient.execute(request);
            // response.getStatusLine().getStatusCode();  
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // long len = entity.getContentLength();// -1 表示长度未知  
                String result = EntityUtils.toString(entity);
                response.close();
                // httpClient.close();  
                return result;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
        return EMPTY_STR;
    }
}

8、WebSecurityConfig

package com.smknet.hmls.preserver.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/**")
                .permitAll()
                .anyRequest()
                .authenticated();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user")
                .password("password")
                .roles("USER");
    }

}

9、EmbeddedServletContainerConfig

package com.smknet.hmls.preserver.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Servlet容器配置
 */
@Component
public class EmbeddedServletContainerConfig implements EmbeddedServletContainerCustomizer {

    @Value("${servlet.container.port}")
    private Integer port;
    @Value("${servlet.container.timeout}")
    private Integer timeout;

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.setPort(port);
        container.setSessionTimeout(timeout, TimeUnit.MINUTES);
    }
}

10、test.html


<html lang="en">
<head>
    <title>测试title>
    <meta charset="utf-8">
head>
<body>
<h1>${user}h1>
body>
html>

11、foo.json 和 mocoserver

打开cmd,转到我们mocoserver的路径下
这里有2个文件,详细看下图
执行下面一段命令,用来启动mocoserver

java -jar moco-runner-0.11.0-standalone.jar start -p 1111 -c foo.json
[   
    {
        "request":{
            "uri":"/UUS001",
            "queries":{
                "accessToken":"123456"
            }
        },
        "response":{
            "json":{"name":"dddddddddddd"}
        }
    }

]

IDEA下创建Springboot,freemarker,mockserver,Gradle项目_第2张图片

IDEA下创建Springboot,freemarker,mockserver,Gradle项目_第3张图片

mocoserver下载地址
我上传的时候发现不能设置0积分。。如有需要,可以私信我邮箱地址,看到肯定第一时间发你~


到这里我们已经完成项目的全部了,可以运行查看效果了哈~

ok~

IDEA下创建Springboot,freemarker,mockserver,Gradle项目_第4张图片


这里打个小广告~

需要看电影的童鞋,可以关注下~

谢谢哈~

IDEA下创建Springboot,freemarker,mockserver,Gradle项目_第5张图片

你可能感兴趣的:(架构设计)