├── webapi ├── src │ ├── main │ │ ├── resources │ │ │ ├── templates │ │ │ │ ├── text │ │ │ │ │ └── text-template.txt │ │ │ │ ├── fragments │ │ │ │ │ ├── alert.html │ │ │ │ │ ├── header.html │ │ │ │ │ └── footer.html │ │ │ │ ├── th-form.html │ │ │ │ ├── layouts │ │ │ │ │ └── layout.html │ │ │ │ ├── scalaexecute.html │ │ │ │ ├── th-objects.html │ │ │ │ └── index.html │ │ │ ├── static │ │ │ │ └── css │ │ │ │ │ └── core.css │ │ │ ├── application.yml │ │ │ ├── Users.xml │ │ │ └── logback.xml │ │ ├── docker │ │ │ └── Dockerfile │ │ ├── java │ │ │ └── com │ │ │ │ └── bob │ │ │ │ └── java │ │ │ │ └── webapi │ │ │ │ ├── constant │ │ │ │ ├── MdcConstans.java │ │ │ │ └── AppConstants.java │ │ │ │ ├── service │ │ │ │ ├── UrlService.java │ │ │ │ ├── RxJavaService.java │ │ │ │ └── CommonService.java │ │ │ │ ├── handler │ │ │ │ ├── MdcPropagatingOnScheduleAction.java │ │ │ │ ├── MdcPropagatingAction0.java │ │ │ │ └── ObservableReturnValueHandler.java │ │ │ │ ├── dto │ │ │ │ ├── RxJavaDTO.java │ │ │ │ └── Form.java │ │ │ │ ├── annotation │ │ │ │ ├── RetryExecution.java │ │ │ │ └── RetryExecutionAspect.java │ │ │ │ ├── spextension │ │ │ │ ├── MDCSimpleAsyncTaskExecutor.java │ │ │ │ ├── MDCAwareCallable.java │ │ │ │ ├── MDCCallableProcessingInterceptor.java │ │ │ │ └── MDCDeferredResultProcessingInterceptor.java │ │ │ │ ├── controller │ │ │ │ ├── ExecuteController.java │ │ │ │ ├── ThymeleafController.java │ │ │ │ ├── CommonController.java │ │ │ │ ├── ThymeleafTextTemplatesController.java │ │ │ │ └── RxJavaController.java │ │ │ │ ├── config │ │ │ │ ├── Thymeleaf3TemplateAvailabilityProvider.java │ │ │ │ └── Thymeleaf3Config.java │ │ │ │ ├── utils │ │ │ │ └── ProtostufUtils.java │ │ │ │ ├── filter │ │ │ │ └── MDCFilter.java │ │ │ │ └── converter │ │ │ │ └── ProtostuffHttpMessageConverter.java │ │ └── scala │ │ │ └── com │ │ │ └── bob │ │ │ └── scala │ │ │ └── webapi │ │ │ ├── utils │ │ │ ├── LoggerObject.scala │ │ │ ├── StringImplicit.scala │ │ │ ├── CodeInvoke.scala │ │ │ └── DistributeLock.scala │ │ │ ├── exception │ │ │ └── Exceptions.scala │ │ │ ├── sptutorial │ │ │ ├── InitHelloWorld.scala │ │ │ └── HelloWorld.scala │ │ │ ├── service │ │ │ └── HelperService.scala │ │ │ ├── messageq │ │ │ └── ObjMsgHandler.scala │ │ │ ├── ApplicationContextHolder.scala │ │ │ ├── aop │ │ │ └── ControllerLogAop.scala │ │ │ ├── controller │ │ │ ├── ProtostufController.scala │ │ │ ├── UserController.scala │ │ │ └── CallableController.scala │ │ │ ├── ScalaApplication.scala │ │ │ └── config │ │ │ ├── SwaggerConfig.scala │ │ │ ├── SpringConfig.scala │ │ │ └── WebConfig.scala │ └── test │ │ └── scala │ │ └── com │ │ └── bob │ │ └── scala │ │ └── webapi │ │ ├── ListTest.scala │ │ └── ProtostufControllerTest.scala └── pom.xml ├── .gitignore ├── README.md ├── pom.xml └── LICENSE /webapi/src/main/resources/templates/text/text-template.txt: -------------------------------------------------------------------------------- 1 | Name: [(${name})] 2 | Link: [(${url})] 3 | Tags: 4 | [# th:each="tag : ${tags}" ] 5 | [(${tag})] 6 | [/] 7 | -------------------------------------------------------------------------------- /webapi/src/main/docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM centos:latest 2 | 3 | MAINTAINER Bob.Wang 4 | 5 | VOLUME /tmp 6 | 7 | WORKDIR /apps/ 8 | 9 | Add springboot-scala-withswagger.jar scalaboot.jar 10 | 11 | EXPOSE 9000 12 | 13 | CMD ["java","-jar","scalaboot.jar"] -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/constant/MdcConstans.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.constant; 2 | 3 | /** 4 | * Created by bob on 17/2/6. 5 | */ 6 | public class MdcConstans { 7 | 8 | public static final String MDC_REMOTE_IP = "remoteIp"; 9 | 10 | public static final String MDC_ClientRequest_ID = "oneRequestId"; 11 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/service/UrlService.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.service; 2 | 3 | import org.springframework.stereotype.Service; 4 | 5 | /** 6 | * Created by bob on 17/3/9. 7 | */ 8 | @Service 9 | public class UrlService { 10 | 11 | public String getApplicationUrl() { 12 | return "domain.com/myapp"; 13 | } 14 | } -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/utils/LoggerObject.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.utils 2 | 3 | import org.slf4j.{LoggerFactory, Logger} 4 | 5 | /** 6 | * Created by bob on 16/2/29. 7 | */ 8 | trait LoggerObject { 9 | /** 10 | * 返回一个记录日志实例 11 | * @return 12 | */ 13 | def LOGGER: Logger = LoggerFactory.getLogger(getClass) 14 | } -------------------------------------------------------------------------------- /webapi/src/main/resources/static/css/core.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-top: 60px; 3 | padding-bottom: 40px; 4 | background-color: #f5f5f5; 5 | } 6 | 7 | .social-links { 8 | max-width: 800px; 9 | margin: 0 auto; 10 | list-style: none; 11 | } 12 | .social-links > li { 13 | width: 30%; 14 | text-align: center; 15 | vertical-align: middle; 16 | display: inline-block; 17 | margin: auto; 18 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/constant/AppConstants.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.constant; 2 | 3 | /** 4 | * Created by bob on 17/2/6. 5 | */ 6 | public class AppConstants { 7 | 8 | public static final String X_REMOTE_IP_HEADER = "X-Remote-IP"; 9 | 10 | public static final String X_FORWARDED_FOR_HEADER = "X-Forwarded-For"; 11 | 12 | public static final String X_Client_Request_Id = "X-Tracking-ID"; 13 | } -------------------------------------------------------------------------------- /webapi/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | swagger: 2 | ui: 3 | enable: true 4 | 5 | helloworld: 6 | message: fuck-62-u 7 | 8 | server: 9 | port: 9999 10 | 11 | spring: 12 | thymeleaf: 13 | cache: true 14 | 15 | management: 16 | security: 17 | enabled: false 18 | 19 | #spring: 20 | # rabbitmq: 21 | # username: root 22 | # password: root 23 | # virtual-host: /order_eventstream 24 | # host: 10.0.40.151 25 | # port: 5672 -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/handler/MdcPropagatingOnScheduleAction.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.handler; 2 | 3 | import rx.functions.Action0; 4 | import rx.functions.Func1; 5 | 6 | /** 7 | * Created by bob on 17/2/9. 8 | */ 9 | public class MdcPropagatingOnScheduleAction implements Func1 { 10 | 11 | @Override 12 | public Action0 call(final Action0 action0) { 13 | return new MdcPropagatingAction0(action0); 14 | } 15 | } -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/exception/Exceptions.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.exception 2 | 3 | /** 4 | * Created by bob on 16/3/2. 5 | */ 6 | case class ClientException(errMessage: String, status: Int = 400) extends Exception(errMessage) { 7 | def this() { 8 | this("", 400) 9 | } 10 | } 11 | 12 | case class ServerException(errMessage: String, status: Int = 500) extends Exception(errMessage) { 13 | def this() { 14 | this("", 500) 15 | } 16 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/dto/RxJavaDTO.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.dto; 2 | 3 | /** 4 | * Created by bob on 17/2/4. 5 | */ 6 | public class RxJavaDTO { 7 | 8 | public String getName() { 9 | return name; 10 | } 11 | 12 | public void setName(String name) { 13 | this.name = name; 14 | } 15 | 16 | private String name; 17 | 18 | public RxJavaDTO() { 19 | 20 | } 21 | 22 | public RxJavaDTO(String name) { 23 | this.name = name; 24 | } 25 | } -------------------------------------------------------------------------------- /webapi/src/main/resources/Users.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | fuck1 4 | 12 5 |
xihu
6 | 1 7 |
8 | 9 | fuck2 10 | 12 11 |
xihuarea
12 | 1 13 |
14 | 15 | abcd 16 | 13 17 |
fuckarea
18 | 2 19 |
20 |
-------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.log 3 | 4 | # build application files 5 | *.apk 6 | *.ap_ 7 | 8 | # file for the dex VM 9 | *.dex 10 | 11 | 12 | # Eclipse project files 13 | .classpath 14 | .project 15 | 16 | # Intellij 17 | *.iml 18 | *.ipr 19 | *.iws 20 | .idea/ 21 | 22 | bin/ 23 | gen/ 24 | 25 | # sbt specific 26 | .cache 27 | .history 28 | .lib/ 29 | dist/* 30 | target/ 31 | lib_managed/ 32 | src_managed/ 33 | project/boot/ 34 | project/plugins/project/ 35 | 36 | # Scala-IDE specific 37 | .scala_dependencies 38 | .worksheet 39 | 40 | .DS_Store -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/utils/StringImplicit.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.utils 2 | 3 | /** 4 | * Created by bob on 16/2/29. 5 | */ 6 | object StringImplicit { 7 | 8 | /** 9 | * 格式化一个字符串,传入Key-Value,字符串中相应的key会被value替换 10 | * 11 | * @param string 12 | * @return 13 | */ 14 | implicit def RichFormatter(string: String) = new { 15 | def richFormat(replacement: Map[String, Any]) = { 16 | (string /: replacement) { (res, entry) => res.replaceAll("#\\{%s\\}".format(entry._1), entry._2.toString) } 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/annotation/RetryExecution.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.annotation; 2 | 3 | import java.lang.annotation.*; 4 | 5 | /** 6 | * Created by bob on 16/8/10. 7 | */ 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target(ElementType.METHOD) 10 | @Inherited 11 | @Documented 12 | public @interface RetryExecution { 13 | 14 | /** 15 | * 重试次数, 默认3次 16 | * 17 | * @return 18 | */ 19 | int retryAttempts() default 3; 20 | 21 | /** 22 | * 重试间隔时间, 默认0秒 23 | * 24 | * @return 25 | */ 26 | long sleepInterval() default 0L; 27 | } -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/sptutorial/InitHelloWorld.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.sptutorial 2 | 3 | import org.springframework.beans.factory.config.BeanPostProcessor 4 | import org.springframework.stereotype.Component 5 | 6 | /** 7 | * Created by bob on 16/6/14. 8 | */ 9 | @Component 10 | class InitHelloWorld extends BeanPostProcessor { 11 | 12 | override def postProcessBeforeInitialization(o: scala.Any, s: String): AnyRef = { 13 | if (s.contains("helloWorld")) { 14 | println(s"init ${s}") 15 | } 16 | o.asInstanceOf[AnyRef] 17 | } 18 | 19 | override def postProcessAfterInitialization(o: scala.Any, s: String): AnyRef = { 20 | if (s.contains("helloWorld")) { 21 | println(s"after ${s}") 22 | } 23 | o.asInstanceOf[AnyRef] 24 | } 25 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/dto/Form.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.dto; 2 | 3 | /** 4 | * Created by bob on 17/3/9. 5 | */ 6 | public class Form { 7 | private String name = "spring.io"; 8 | private String url = "http://spring.io"; 9 | private String tags = "#spring #framework #java"; 10 | 11 | public String getName() { 12 | return name; 13 | } 14 | 15 | public void setName(String name) { 16 | this.name = name; 17 | } 18 | 19 | public String getUrl() { 20 | return url; 21 | } 22 | 23 | public void setUrl(String url) { 24 | this.url = url; 25 | } 26 | 27 | public String getTags() { 28 | return tags; 29 | } 30 | 31 | public void setTags(String tags) { 32 | this.tags = tags; 33 | } 34 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/spextension/MDCSimpleAsyncTaskExecutor.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.spextension; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.slf4j.MDC; 6 | import org.springframework.core.task.SimpleAsyncTaskExecutor; 7 | 8 | import static com.bob.java.webapi.spextension.MDCAwareCallable.wrap; 9 | 10 | /** 11 | * Created by bob on 17/2/8. 12 | */ 13 | public class MDCSimpleAsyncTaskExecutor extends SimpleAsyncTaskExecutor { 14 | 15 | private Logger log = LoggerFactory.getLogger(MDCSimpleAsyncTaskExecutor.class); 16 | 17 | @Override 18 | public void execute(Runnable task, long startTimeout) { 19 | 20 | log.info("MDCSimpleAsyncTaskExecutor begin to execute"); 21 | super.execute(wrap(task, MDC.getCopyOfContextMap()), startTimeout); 22 | log.info("MDCSimpleAsyncTaskExecutor stop to execute"); 23 | } 24 | } -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/utils/CodeInvoke.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.utils 2 | 3 | import scala.reflect.runtime.currentMirror 4 | import scala.tools.reflect.ToolBox 5 | 6 | /** 7 | * Created by wangxiang on 17/9/12. 8 | */ 9 | object CodeInvoke { 10 | 11 | private val toolbox = currentMirror.mkToolBox() 12 | 13 | def invoke(code: String) = { 14 | // import scala.reflect.runtime.universe._ 15 | // val qcode = q"""$code""" 16 | // val rs = toolbox.compile(qcode)() 17 | 18 | val rs = toolbox.eval(toolbox.parse(code)) 19 | rs 20 | } 21 | 22 | def a(): String = { 23 | val a = 24 | """ 25 | | import com.bob.scala.webapi.ApplicationContextHolder 26 | | import com.bob.scala.webapi.service.HelperService 27 | | val l = ApplicationContextHolder.getBean(classOf[HelperService]) 28 | | val s = l.handlerInput("hello") 29 | | s 30 | """.stripMargin 31 | a 32 | } 33 | } -------------------------------------------------------------------------------- /webapi/src/main/resources/templates/fragments/alert.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 10 | 12 | 13 | 14 |
15 | 16 | Test 17 |
18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/sptutorial/HelloWorld.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.sptutorial 2 | 3 | import javax.annotation.{PostConstruct, PreDestroy} 4 | 5 | import org.springframework.beans.factory.annotation.Value 6 | import org.springframework.stereotype.Component 7 | 8 | import scala.beans.BeanProperty 9 | 10 | /** 11 | * Created by bob on 16/6/14. 12 | */ 13 | @Component 14 | class HelloWorld { 15 | 16 | @PostConstruct 17 | def init() { 18 | println("HelloWorld Bean is going through init.") 19 | } 20 | 21 | @PreDestroy 22 | def destory() { 23 | println("HelloWorld Bean is going through destroy.") 24 | } 25 | 26 | @BeanProperty 27 | @Value("${helloworld.message}") 28 | var message: String = _ 29 | 30 | /** 31 | * Spring Bean definition inheritance has nothing to do with Java class inheritance but inheritance concept is same. 32 | * You can define a parent bean definition as a template and other child beans can inherit required configuration from the parent bean. 33 | */ 34 | 35 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/controller/ExecuteController.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.controller; 2 | 3 | import com.bob.scala.webapi.utils.CodeInvoke; 4 | import com.google.common.collect.Maps; 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.web.bind.annotation.*; 7 | 8 | import java.util.Date; 9 | import java.util.Map; 10 | 11 | /** 12 | * Created by wangxiang on 17/9/12. 13 | */ 14 | @Controller 15 | public class ExecuteController { 16 | 17 | @GetMapping("/scalaexecute") 18 | public String gScalaExecute() { 19 | return "scalaexecute"; 20 | } 21 | 22 | @RequestMapping(method = RequestMethod.POST, value = "/scalaexecute") 23 | @ResponseBody 24 | public Map pScalaExecute(@RequestBody Map jsonNodes) { 25 | Map map = Maps.newHashMap(); 26 | String rs = jsonNodes.get("content"); 27 | map.put("rs", CodeInvoke.invoke(rs).toString()); 28 | map.put("now", new Date().toString()); 29 | return map; 30 | } 31 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/handler/MdcPropagatingAction0.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.handler; 2 | 3 | import org.slf4j.MDC; 4 | import rx.functions.Action0; 5 | 6 | import java.util.Map; 7 | 8 | /** 9 | * 重写Action0,使其将当前线程的MDC值传递到下个线程中 10 | *

11 | * Created by bob on 17/2/9. 12 | */ 13 | public class MdcPropagatingAction0 implements Action0 { 14 | 15 | private final Action0 action0; 16 | private final Map context; 17 | 18 | public MdcPropagatingAction0(final Action0 action0) { 19 | this.action0 = action0; 20 | this.context = MDC.getCopyOfContextMap(); 21 | } 22 | 23 | @Override 24 | public void call() { 25 | final Map originalMdc = MDC.getCopyOfContextMap(); 26 | if (context != null) { 27 | MDC.setContextMap(context); 28 | } 29 | try { 30 | this.action0.call(); 31 | } finally { 32 | if (originalMdc != null) { 33 | MDC.setContextMap(originalMdc); 34 | } 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/service/RxJavaService.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.service; 2 | 3 | import com.bob.java.webapi.dto.RxJavaDTO; 4 | import com.bob.scala.webapi.service.HelperService; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Service; 9 | import rx.Observable; 10 | 11 | /** 12 | * Created by bob on 17/2/4. 13 | */ 14 | @Service 15 | public class RxJavaService { 16 | 17 | private Logger log = LoggerFactory.getLogger(RxJavaService.class); 18 | 19 | @Autowired 20 | private HelperService helperService; 21 | 22 | public Observable compose(String name) { 23 | return Observable.create(sub -> { 24 | RxJavaDTO item = getRxJavaDTO(name); 25 | sub.onNext(item); 26 | sub.onCompleted(); 27 | }); 28 | } 29 | 30 | public RxJavaDTO getRxJavaDTO(String name) { 31 | RxJavaDTO item = new RxJavaDTO(); 32 | item.setName(helperService.handlerInput(name)); 33 | return item; 34 | } 35 | } -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/service/HelperService.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.service 2 | 3 | import com.bob.java.webapi.constant.MdcConstans 4 | import org.slf4j.{Logger, LoggerFactory, MDC} 5 | import org.springframework.stereotype.Service 6 | import org.springframework.util.StringUtils 7 | 8 | /** 9 | * Created by bob on 17/2/6. 10 | */ 11 | @Service 12 | class HelperService { 13 | 14 | private val LOGGER: Logger = LoggerFactory.getLogger(classOf[HelperService]) 15 | 16 | def handlerInput(param: String): String = { 17 | LOGGER.info(s"handlerInputParm/${param} begin to process") 18 | Thread.sleep(1000 * 2) 19 | val sb: StringBuilder = new StringBuilder(param) 20 | var value: String = MDC.get(MdcConstans.MDC_REMOTE_IP) 21 | if (!StringUtils.isEmpty(value)) { 22 | sb.append("\r remoteip is " + value) 23 | } else { 24 | sb.append("\r remoteip is empty") 25 | } 26 | value = MDC.get(MdcConstans.MDC_ClientRequest_ID) 27 | if (!StringUtils.isEmpty(value)) sb.append("\r clientid is " + value) 28 | else { 29 | sb.append("\r clientid is empty") 30 | } 31 | LOGGER.info(s"handlerInputParm/${param} stop to process") 32 | sb.toString 33 | } 34 | } -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/messageq/ObjMsgHandler.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.messageq 2 | 3 | import java.nio.charset.StandardCharsets 4 | 5 | import org.slf4j.{Logger, LoggerFactory} 6 | import org.springframework.amqp.core.Message 7 | import org.springframework.amqp.support.converter.SimpleMessageConverter 8 | import org.springframework.beans.factory.annotation.Autowired 9 | import org.springframework.stereotype.Service 10 | 11 | /** 12 | * Created by bob on 16/12/24. 13 | */ 14 | @Service 15 | class ObjMsgHandler { 16 | 17 | private val LOGGER: Logger = LoggerFactory.getLogger(classOf[ObjMsgHandler]) 18 | @Autowired private val simpleMessageConverter: SimpleMessageConverter = null 19 | 20 | // @RabbitListener(queues = Array("ordera")) 21 | def handlerA(message: Message) { 22 | val m = message2String(message) 23 | LOGGER.info(s"aaaa - ${m}") 24 | } 25 | 26 | def message2String(message: Message): String = { 27 | val obj = simpleMessageConverter.fromMessage(message) 28 | if (obj.isInstanceOf[String]) { 29 | obj.asInstanceOf[String] 30 | } else if (obj.isInstanceOf[Array[Byte]]) { 31 | return new String(obj.asInstanceOf[Array[Byte]], StandardCharsets.UTF_8.name()) 32 | } 33 | return obj.toString 34 | } 35 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/controller/ThymeleafController.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.controller; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.ui.Model; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.ModelAttribute; 7 | 8 | import javax.servlet.http.HttpSession; 9 | import java.util.Arrays; 10 | import java.util.List; 11 | 12 | /** 13 | * Created by bob on 17/3/8. 14 | * http://blog.codeleak.pl/2014/05/spring-mvc-and-thymeleaf-how-to-acess-data-from-templates.html 15 | */ 16 | @Controller 17 | public class ThymeleafController { 18 | 19 | @ModelAttribute("messages") 20 | List messages() { 21 | return Arrays.asList("Message 1", "Message 2", "Message 3"); 22 | } 23 | 24 | @GetMapping("/model-attr") 25 | String modelAttributes(Model model) { 26 | return "th-objects"; 27 | } 28 | 29 | @GetMapping("/query-params") 30 | String queryParams() { 31 | return "redirect:/model-attr?q=My Query"; 32 | } 33 | 34 | @GetMapping("/session-attr") 35 | String sessionAttributes(HttpSession session) { 36 | session.setAttribute("mySessionAttribute", "Session Attr 1"); 37 | return "th-objects"; 38 | } 39 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/spextension/MDCAwareCallable.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.spextension; 2 | 3 | import org.slf4j.MDC; 4 | 5 | import java.util.Map; 6 | import java.util.concurrent.Callable; 7 | 8 | /** 9 | * Created by bob on 17/2/9. 10 | */ 11 | public final class MDCAwareCallable { 12 | public static Callable wrapCallable(final Callable callable) { 13 | final Map context = MDC.getCopyOfContextMap(); 14 | return () -> { 15 | if (context != null) { 16 | MDC.setContextMap(context); 17 | } 18 | try { 19 | return callable.call(); 20 | } catch (Exception e) { 21 | return null; 22 | } 23 | }; 24 | } 25 | 26 | public static Runnable wrap(final Runnable runnable, final Map context) { 27 | return () -> { 28 | Map previous = MDC.getCopyOfContextMap(); 29 | if (context == null) { 30 | MDC.clear(); 31 | } else { 32 | MDC.setContextMap(context); 33 | } 34 | try { 35 | runnable.run(); 36 | } finally { 37 | if (previous == null) { 38 | MDC.clear(); 39 | } else { 40 | MDC.setContextMap(previous); 41 | } 42 | } 43 | }; 44 | } 45 | } -------------------------------------------------------------------------------- /webapi/src/main/resources/templates/fragments/header.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 11 | 13 | 14 | 15 | 16 | 17 |

35 | 36 | -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/config/Thymeleaf3TemplateAvailabilityProvider.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.config; 2 | 3 | import org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider; 4 | import org.springframework.boot.bind.RelaxedPropertyResolver; 5 | import org.springframework.core.env.Environment; 6 | import org.springframework.core.env.PropertyResolver; 7 | import org.springframework.core.io.ResourceLoader; 8 | import org.springframework.util.ClassUtils; 9 | 10 | /** 11 | * Created by bob on 17/3/9. 12 | */ 13 | public class Thymeleaf3TemplateAvailabilityProvider implements TemplateAvailabilityProvider { 14 | 15 | private static final String DEFAULT_PREFIX = "classpath:/templates/"; 16 | private static final String DEFAULT_SUFFIX = ".html"; 17 | 18 | @Override 19 | public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, 20 | ResourceLoader resourceLoader) { 21 | 22 | if (ClassUtils.isPresent("org.thymeleaf.spring4.SpringTemplateEngine", classLoader) 23 | && ClassUtils.isPresent("org.thymeleaf.Thymeleaf", classLoader)) { 24 | PropertyResolver resolver = new RelaxedPropertyResolver(environment, "spring.thymeleaf3."); 25 | String prefix = resolver.getProperty("prefix", DEFAULT_PREFIX); 26 | String suffix = resolver.getProperty("suffix", DEFAULT_SUFFIX); 27 | return resourceLoader.getResource(prefix + view + suffix).exists(); 28 | } 29 | return false; 30 | } 31 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/controller/CommonController.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.controller; 2 | 3 | import com.bob.java.webapi.service.CommonService; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RequestMethod; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | /** 13 | * Created by bob on 17/2/8. 14 | */ 15 | @RestController 16 | @RequestMapping(value = "common/v1") 17 | public class CommonController { 18 | 19 | private static final Logger log = LoggerFactory.getLogger(CommonController.class); 20 | 21 | @Autowired 22 | private CommonService commonService; 23 | 24 | @RequestMapping(value = "chandle/{name}", method = RequestMethod.GET) 25 | public String chandle( 26 | @PathVariable("name") String name) { 27 | log.info("rs/chandle/ begin to process"); 28 | String temp = name.concat("-other-name-").concat(name); 29 | log.info("rs/chandle/ stop to process"); 30 | return temp; 31 | } 32 | 33 | @RequestMapping(value = "asynchandle/{name}", method = RequestMethod.GET) 34 | public String asynchandle( 35 | @PathVariable("name") String name) { 36 | log.info("rs/asynchandle/ begin to process"); 37 | commonService.getRxJavaDTO(name); 38 | log.info("rs/asynchandle/ stop to process"); 39 | return name; 40 | } 41 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/controller/ThymeleafTextTemplatesController.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.controller; 2 | 3 | import com.bob.java.webapi.dto.Form; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.ui.Model; 7 | import org.springframework.validation.support.BindingAwareModelMap; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.ModelAttribute; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.thymeleaf.TemplateEngine; 13 | import org.thymeleaf.context.Context; 14 | 15 | /** 16 | * Created by bob on 17/3/9. 17 | */ 18 | @Controller 19 | @RequestMapping("/text-templates") 20 | public class ThymeleafTextTemplatesController { 21 | 22 | @Autowired 23 | private TemplateEngine templateEngine; 24 | 25 | @GetMapping("/form") 26 | public String form(Model model) { 27 | model.addAttribute(new Form()); 28 | return "th-form"; 29 | } 30 | 31 | @PostMapping("/form") 32 | public String postForm(@ModelAttribute Form form) { 33 | 34 | Model model = new BindingAwareModelMap(); 35 | 36 | Context context = new Context(); 37 | context.setVariable("name", form.getName()); 38 | context.setVariable("url", form.getUrl()); 39 | context.setVariable("tags", form.getTags().split(" ")); 40 | 41 | String text = templateEngine.process("text-template", context); 42 | 43 | model.addAttribute("text", text); 44 | 45 | return "th-form"; 46 | } 47 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/service/CommonService.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.service; 2 | 3 | import com.bob.java.webapi.constant.MdcConstans; 4 | import com.bob.java.webapi.dto.RxJavaDTO; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.slf4j.MDC; 8 | import org.springframework.scheduling.annotation.Async; 9 | import org.springframework.scheduling.annotation.AsyncResult; 10 | import org.springframework.stereotype.Service; 11 | import org.springframework.util.StringUtils; 12 | 13 | import java.util.concurrent.Future; 14 | 15 | /** 16 | * Created by bob on 17/2/8. 17 | */ 18 | @Service 19 | public class CommonService { 20 | 21 | private Logger log = LoggerFactory.getLogger(CommonService.class); 22 | 23 | /** 24 | * 异步执行,需要返回的Future<>类型 25 | * 26 | * @param name 27 | * @return 28 | */ 29 | @Async 30 | public Future getRxJavaDTO(String name) { 31 | try { 32 | Thread.sleep(100); 33 | } catch (InterruptedException e) { 34 | e.printStackTrace(); 35 | } 36 | log.info("common service begin to process"); 37 | RxJavaDTO item = new RxJavaDTO(); 38 | item.setName(name); 39 | String value = MDC.get(MdcConstans.MDC_REMOTE_IP); 40 | if (!StringUtils.isEmpty(value)) { 41 | log.info("remoteid id " + value); 42 | } else { 43 | log.info("remoteid id is empty"); 44 | } 45 | value = MDC.get(MdcConstans.MDC_ClientRequest_ID); 46 | if (!StringUtils.isEmpty(value)) { 47 | log.info("client id " + value); 48 | } else { 49 | log.info("client id is empty"); 50 | } 51 | log.info("common service end to process"); 52 | return new AsyncResult<>(item); 53 | } 54 | } -------------------------------------------------------------------------------- /webapi/src/main/resources/templates/fragments/footer.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 |
10 | 23 |
24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/controller/RxJavaController.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.controller; 2 | 3 | import com.bob.java.webapi.dto.RxJavaDTO; 4 | import com.bob.java.webapi.service.RxJavaService; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.http.MediaType; 9 | import org.springframework.web.bind.annotation.PathVariable; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RequestMethod; 12 | import org.springframework.web.bind.annotation.RestController; 13 | import rx.Observable; 14 | 15 | /** 16 | * 异步例子,返回RxJava的可观察容器 17 | * Created by bob on 17/2/4. 18 | */ 19 | @RestController 20 | @RequestMapping(value = "rxjava/v1") 21 | public class RxJavaController { 22 | 23 | private static final Logger log = LoggerFactory.getLogger(RxJavaController.class); 24 | 25 | @Autowired 26 | private RxJavaService rxJavaService; 27 | 28 | @RequestMapping(value = "/rx/observable/{name}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}) 29 | public Observable observable( 30 | @PathVariable("name") String name) { 31 | log.info("rs/observable/ begin to process"); 32 | Observable temp = rxJavaService.compose(name); 33 | log.info("rs/observable/ stop to process"); 34 | return temp; 35 | } 36 | 37 | @RequestMapping(value = "/rx/noobservable/{name}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}) 38 | public RxJavaDTO noobservable(@PathVariable("name") String name) { 39 | log.info("rs/noobservable/ begin to process"); 40 | RxJavaDTO temp = rxJavaService.getRxJavaDTO(name); 41 | log.info("rs/noobservable/ stop to process"); 42 | return temp; 43 | } 44 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/spextension/MDCCallableProcessingInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.spextension; 2 | 3 | import com.bob.java.webapi.constant.MdcConstans; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.slf4j.MDC; 7 | import org.springframework.web.context.request.NativeWebRequest; 8 | import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; 9 | 10 | import java.util.Map; 11 | import java.util.concurrent.Callable; 12 | 13 | /** 14 | * 直接返回callable跟webasynctask都会调用此类,在before**中将当前线程的MDC值设置到request中,这样可以在pre**中得到 15 | * 添加拦截器是一种方案,但也可以自定义一个SimpleAsyncTaskExecutor,在那重写execute方法将MDC值进行传递,并成为IOC的bean,参见WebConfig类 16 | * Created by bob on 17/2/8. 17 | */ 18 | public class MDCCallableProcessingInterceptor extends CallableProcessingInterceptorAdapter { 19 | 20 | private static final Logger log = LoggerFactory.getLogger(MDCCallableProcessingInterceptor.class); 21 | 22 | @Override 23 | public void beforeConcurrentHandling(NativeWebRequest request, Callable task) throws Exception { 24 | // 经测试,是Tomcat的请求线程 25 | log.info("client id -> " + MDC.get(MdcConstans.MDC_ClientRequest_ID)); 26 | log.info("remote ip -> " + MDC.get(MdcConstans.MDC_REMOTE_IP)); 27 | request.setAttribute("mdcmap", MDC.getCopyOfContextMap(), -1); 28 | super.beforeConcurrentHandling(request, task); 29 | } 30 | 31 | @Override 32 | public void preProcess(NativeWebRequest request, Callable task) throws Exception { 33 | // 经测试,在这已经是工作线程,Tomcat的请求线程已经释放,在这直接拿MDC值的话为空 34 | Map map = (Map) request.getAttribute("mdcmap", -1); 35 | log.info("preProcess client id -> " + map.get(MdcConstans.MDC_ClientRequest_ID)); 36 | log.info("preProcess remote ip -> " + map.get(MdcConstans.MDC_REMOTE_IP)); 37 | MDC.setContextMap(map); 38 | super.preProcess(request, task); 39 | } 40 | } -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/ApplicationContextHolder.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi 2 | 3 | import java.util 4 | import java.util.{Objects} 5 | 6 | import org.springframework.beans.BeansException 7 | import org.springframework.beans.factory.DisposableBean 8 | import org.springframework.context.{ApplicationContext, ApplicationContextAware} 9 | 10 | /** 11 | * Created by wangxiang on 17/9/12. 12 | */ 13 | object ApplicationContextHolder { 14 | 15 | def getAppCtx: ApplicationContext = appCtx 16 | 17 | private var appCtx: ApplicationContext = null 18 | 19 | private def cleanApplicationContext(): Unit = { 20 | appCtx = null 21 | } 22 | 23 | @SuppressWarnings(Array("unchecked")) 24 | @throws[BeansException] 25 | def getBean[T](name: String): T = { 26 | checkApplicationContext() 27 | appCtx.getBean(name).asInstanceOf[T] 28 | } 29 | 30 | @SuppressWarnings(Array("unchecked")) 31 | @throws[BeansException] 32 | def getBean[T](clazz: Class[T]): T = { 33 | checkApplicationContext() 34 | appCtx.getBean(clazz) 35 | } 36 | 37 | @SuppressWarnings(Array("unchecked")) 38 | @throws[BeansException] 39 | def getBeansOfType[T](clazz: Class[T]): util.Map[String, T] = { 40 | checkApplicationContext() 41 | appCtx.getBeansOfType(clazz) 42 | } 43 | 44 | private def checkApplicationContext(): Unit = { 45 | if (appCtx == null) throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder") 46 | } 47 | } 48 | 49 | final class ApplicationContextHolder extends ApplicationContextAware with DisposableBean { 50 | @throws[Exception] 51 | override def destroy(): Unit = { 52 | ApplicationContextHolder.cleanApplicationContext() 53 | } 54 | 55 | override def setApplicationContext(appCtx: ApplicationContext): Unit = { 56 | Objects.requireNonNull(appCtx, "Application Context is required") 57 | ApplicationContextHolder.appCtx = appCtx 58 | } 59 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Description 2 | 3 | * A basic guide using spring boot in scala combine swagger 4 | * Update jdk version to 1.8, for using lambda 5 | * Action can return the rx.Observable, like return Callable Or DeferredResult see the **RxJavaController** 6 | * When controller return Callable/DeferredResult/Observable, Support MDC value to deliver 7 | 8 | # Prerequisite 9 | 10 | * [Spring-boot](http://projects.spring.io/spring-boot) 11 | * [Scala](http://www.scala-lang.org) 12 | * [Swagger](http://swagger.io) 13 | * [Maven](http://maven.apache.org) 14 | * [Docker](http://www.docker.com) 15 | * [RxJava](https://github.com/ReactiveX/RxJava) 16 | 17 | # Maven/sbt 18 | why this using maven not sbt,just for convenient because we can inhert 'spring-boot-starter-parent', 19 | so everything we no need to care the jar version. also it is ok for using sbt to manage the package. 20 | 21 | # Structure 22 | * aop, around every request and response 23 | * config, deploy the property for app 24 | * controller, handle the request and return response 25 | * exception, where to handle overall exception 26 | * utils, some useful function, like distribute lock and expend method 27 | 28 | # Special Point 29 | 30 | * ProtostuffHttpMessageConverter 31 | > 使用**io.protostuff**来进行数据传输 32 | 33 | * ObservableReturnValueHandler 34 | > 继承**AsyncHandlerMethodReturnValueHandler**类, 使**spring mvc**可以返回Observable类型, 这样可以避免**web server**的连接池被占用而引起性能问题,增加服务器的吞吐量 35 | 36 | * MDCSimpleAsyncTaskExecutor/MDCCallableProcessingInterceptor/MdcPropagatingOnScheduleAction 37 | > 像**spring mvc**返回**Callable/DeferredResult**等类型时,本质上都是为了避免**web server**线程池被占用,利用非web的服务线程来处理,这个时候如果我们使用了**slf4j**中的**MDC**类时或者**jdk**的**threadlocal**时, 我们需要将请求线程中的一些数据给传递下去, 像**traceid**这种全链路调用标识符, 那我们就需要扩展**CallableProcessingInterceptorAdapter**跟**DeferredResultProcessingInterceptorAdapter**这类型, 在线程执行前后将当前线程的数据给传递到新起来的线程中 38 | 39 | * others 40 | > 如果是**spring cloud**中, 那我们也可以在跟其它服务进行交互时重写一些, 像**feignClient**中的**RequestInterceptor**拦截器, 在这添加我们自己的特殊处理 41 | 42 | -------------------------------------------------------------------------------- /webapi/src/main/resources/templates/th-form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Hello Spring Boot! 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 |
15 |
16 |
17 | 18 | 19 |
20 |
21 | 22 | 23 |
24 |
25 | 26 | 27 |
28 | 29 |
30 |
31 |
32 |

Processed text template

33 |
34 |                 Demo
35 |             
36 |
37 |
38 |
39 | 40 | -------------------------------------------------------------------------------- /webapi/src/main/resources/templates/layouts/layout.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | Hello Spring Boot! 7 | 8 | 11 | 14 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 37 |
38 |
39 |
40 |

Content goes here...

41 |
42 |
43 |
© 2017 blog.codeleak.pl
44 |
45 |
46 | 47 | -------------------------------------------------------------------------------- /webapi/src/main/resources/templates/scalaexecute.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | execute 4 | 5 | 6 | 7 | 8 |
9 | 11 | 12 |
13 | 15 | 16 |
17 |
18 | 19 | 56 | -------------------------------------------------------------------------------- /webapi/src/test/scala/com/bob/scala/webapi/ListTest.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi 2 | 3 | import java.io.{File, FilenameFilter} 4 | import java.util 5 | import java.util.Date 6 | 7 | import org.junit.Test 8 | 9 | /** 10 | * Created by bob on 17/2/10. 11 | */ 12 | class ListTest { 13 | 14 | case class User(userid: Long, createat: Date, id: Long) 15 | 16 | @Test 17 | def testStub(): Unit = { 18 | val f = new File("/Users/bob/Works/enniu/JProject/fc-risk-dataapi") 19 | if (!f.isDirectory) { 20 | return 21 | } 22 | val fd = depthScaner(f, "java") 23 | import collection.JavaConverters._ 24 | fd.asScala.foreach(println) 25 | println("*****-----" * 5) 26 | val fw = widthScaner(f, "java") 27 | fw.asScala.foreach(println) 28 | } 29 | 30 | case class BBFileFilter(suffix: String) extends FilenameFilter { 31 | def accept(dir: File, name: String): Boolean = { 32 | val f = new File(dir, name) 33 | if (f.isFile) { 34 | return f.getName.endsWith(suffix) 35 | } 36 | return true 37 | } 38 | } 39 | 40 | /** 41 | * 深度搜索 42 | * 43 | * @param path 44 | * @param suffix 45 | */ 46 | def depthScaner(path: File, suffix: String): util.ArrayList[String] = { 47 | val list = new util.ArrayList[String]() 48 | val fs = path.listFiles(BBFileFilter(suffix)) 49 | for (f: File <- fs) { 50 | if (f.isDirectory) { 51 | list.addAll(depthScaner(f, suffix)) 52 | } else { 53 | list.add(f.getAbsolutePath) 54 | } 55 | } 56 | list 57 | } 58 | 59 | /** 60 | * 广度搜索 61 | * 62 | * @param path 63 | * @param suffix 64 | */ 65 | def widthScaner(path: File, suffix: String): util.ArrayList[String] = { 66 | val list = new util.ArrayList[String]() 67 | 68 | val queue = new util.ArrayDeque[File]() 69 | queue.offer(path) 70 | val filter = BBFileFilter(suffix) 71 | 72 | while (!queue.isEmpty) { 73 | val p = queue.poll() 74 | val fs = p.listFiles(filter) 75 | for (f <- fs) { 76 | if (f.isFile) { 77 | list.add(f.getAbsolutePath) 78 | } else { 79 | queue.offer(f) 80 | } 81 | } 82 | } 83 | 84 | list 85 | } 86 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/utils/ProtostufUtils.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.utils; 2 | 3 | import io.protostuff.LinkedBuffer; 4 | import io.protostuff.ProtostuffIOUtil; 5 | import io.protostuff.Schema; 6 | import io.protostuff.runtime.RuntimeSchema; 7 | import org.springframework.objenesis.Objenesis; 8 | import org.springframework.objenesis.ObjenesisStd; 9 | 10 | import java.util.Map; 11 | import java.util.concurrent.ConcurrentHashMap; 12 | 13 | /** 14 | * Created by bob on 17/2/7. 15 | */ 16 | public class ProtostufUtils { 17 | 18 | private static Map, Schema> cachedSchema = new ConcurrentHashMap<>(); 19 | 20 | private static Objenesis objenesis = new ObjenesisStd(true); 21 | 22 | private ProtostufUtils() { 23 | } 24 | 25 | @SuppressWarnings("unchecked") 26 | private static Schema getSchema(Class clasz) { 27 | Schema schema = (Schema) cachedSchema.get(clasz); 28 | if (schema == null) { 29 | schema = RuntimeSchema.createFrom(clasz); 30 | if (schema != null) { 31 | cachedSchema.put(clasz, schema); 32 | } 33 | } 34 | return schema; 35 | } 36 | 37 | /** 38 | * 序列化 39 | * 40 | * @param obj 41 | * @param 42 | * @return 43 | */ 44 | @SuppressWarnings("unchecked") 45 | public static byte[] serialize(T obj) { 46 | Class clasz = (Class) obj.getClass(); 47 | LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); 48 | try { 49 | Schema schema = getSchema(clasz); 50 | return ProtostuffIOUtil.toByteArray(obj, schema, buffer); 51 | } catch (Exception e) { 52 | throw new IllegalStateException(e.getMessage(), e); 53 | } finally { 54 | buffer.clear(); 55 | } 56 | } 57 | 58 | /** 59 | * 反序列化 60 | * 61 | * @param data 62 | * @param clasz 63 | * @param 64 | * @return 65 | */ 66 | public static T deserialize(byte[] data, Class clasz) { 67 | try { 68 | T message = objenesis.newInstance(clasz); 69 | Schema schema = getSchema(clasz); 70 | ProtostuffIOUtil.mergeFrom(data, message, schema); 71 | return message; 72 | } catch (Exception e) { 73 | throw new IllegalStateException(e.getMessage(), e); 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/aop/ControllerLogAop.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.aop 2 | 3 | import java.lang.reflect.Method 4 | 5 | import com.bob.scala.webapi.utils.LoggerObject 6 | import com.bob.scala.webapi.utils.StringImplicit.RichFormatter 7 | import com.fasterxml.jackson.databind.ObjectMapper 8 | import org.aspectj.lang.ProceedingJoinPoint 9 | import org.aspectj.lang.annotation.{Around, Aspect} 10 | import org.aspectj.lang.reflect.MethodSignature 11 | import org.springframework.beans.factory.annotation.Autowired 12 | import org.springframework.stereotype.Component 13 | 14 | /** 15 | * Created by bob on 16/2/29. 16 | */ 17 | @Component 18 | @Aspect 19 | class ControllerLogAop extends LoggerObject { 20 | 21 | @Autowired 22 | var objectMapper: ObjectMapper = _ 23 | 24 | @Around("execution(* com.bob.*.webapi.controller.*.*(..))") 25 | def doAroundMapper(proceedingJoinPoint: ProceedingJoinPoint): Object = { 26 | val signature: MethodSignature = proceedingJoinPoint.getSignature.asInstanceOf[MethodSignature] 27 | val method: Method = signature.getMethod 28 | val className = proceedingJoinPoint.getTarget.getClass.getName 29 | 30 | val start = System.currentTimeMillis() 31 | LOGGER.info("executing controller %s method %s request params %s and time is %s".format(className, method.getName, 32 | objectMapper.writeValueAsString(proceedingJoinPoint.getArgs), start)) 33 | 34 | var result: Object = null 35 | try { 36 | result = proceedingJoinPoint.proceed 37 | } 38 | catch { 39 | case throwable: Throwable => { 40 | throw throwable 41 | } 42 | } 43 | val end = System.currentTimeMillis() 44 | if (LOGGER.isInfoEnabled) { 45 | if (!result.isInstanceOf[rx.Observable[_]]) { 46 | LOGGER.info("executed controller #{controllername} method #{methodname} response #{response} and total time is #{time} ms" 47 | .richFormat( 48 | Map("controllername" -> className, 49 | "methodname" -> method.getName, 50 | "response" -> objectMapper.writeValueAsString(method.getReturnType.cast(result)), 51 | "time" -> (end - start)))) 52 | } 53 | } 54 | else { 55 | LOGGER.info("executed controller #{controllername} method #{methodname} response #{response} and total time is #{time} ms" 56 | .richFormat( 57 | Map("controllername" -> className, 58 | "methodname" -> method.getName, 59 | "time" -> (end - start)))) 60 | } 61 | result 62 | } 63 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/handler/ObservableReturnValueHandler.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.handler; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.core.MethodParameter; 6 | import org.springframework.web.context.request.NativeWebRequest; 7 | import org.springframework.web.context.request.async.DeferredResult; 8 | import org.springframework.web.context.request.async.WebAsyncUtils; 9 | import org.springframework.web.method.support.AsyncHandlerMethodReturnValueHandler; 10 | import org.springframework.web.method.support.ModelAndViewContainer; 11 | import rx.Observable; 12 | import rx.schedulers.Schedulers; 13 | 14 | /** 15 | * Created by bob on 17/1/4. 16 | */ 17 | public class ObservableReturnValueHandler implements AsyncHandlerMethodReturnValueHandler { 18 | 19 | private static final Logger log = LoggerFactory.getLogger(ObservableReturnValueHandler.class); 20 | 21 | @Override 22 | public boolean isAsyncReturnValue(Object returnValue, MethodParameter returnType) { 23 | return returnValue != null && supportsReturnType(returnType); 24 | } 25 | 26 | @Override 27 | public boolean supportsReturnType(MethodParameter returnType) { 28 | return Observable.class.isAssignableFrom(returnType.getParameterType()); 29 | } 30 | 31 | @Override 32 | public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { 33 | 34 | if (returnValue == null) { 35 | mavContainer.setRequestHandled(true); 36 | return; 37 | } 38 | 39 | final Observable observable = Observable.class.cast(returnValue); 40 | log.debug("handleReturnValue begin to process"); 41 | WebAsyncUtils.getAsyncManager(webRequest) 42 | .startDeferredResultProcessing(new ObservableAdapter<>(observable), mavContainer); 43 | log.debug("handleReturnValue stop to process"); 44 | } 45 | 46 | public class ObservableAdapter extends DeferredResult { 47 | public ObservableAdapter(Observable observable) { 48 | log.debug("observableAdapter begin to process"); 49 | observable.subscribeOn(Schedulers.newThread()) 50 | .subscribe( 51 | t -> { 52 | setResult(t); 53 | log.info("observableAdapter set the result value to DeferredResult"); 54 | }, 55 | throwable -> setErrorResult(throwable) 56 | ); 57 | log.debug("observableAdapter stop to process"); 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /webapi/src/main/resources/templates/th-objects.html: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | Hello Spring Boot! 8 | 9 | 12 | 15 | 17 | 18 | 19 | 20 | 21 |
22 |

Model Attributes

23 |
    24 | Message 25 |
26 |
27 | 28 |
29 |

Query Params

30 |

Test

31 |

Test

32 |

Test

33 |
34 | 35 |
36 |

Session Attributes

37 |

[...]

38 |

[...]

39 |
40 | 41 |
42 |

Servlet Context

43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 |
My context attribute42
javax.servlet.context.tempdir/tmp
54 |
55 | 56 |
57 |

Spring Beans

58 | 59 |

...

60 |
61 | 62 |
63 | 64 | -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/annotation/RetryExecutionAspect.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.annotation; 2 | 3 | import org.aspectj.lang.ProceedingJoinPoint; 4 | import org.aspectj.lang.annotation.Around; 5 | import org.aspectj.lang.annotation.Aspect; 6 | import org.aspectj.lang.reflect.MethodSignature; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.stereotype.Component; 10 | 11 | import java.lang.reflect.Method; 12 | 13 | /** 14 | * Created by bob on 16/8/10. 15 | */ 16 | @Aspect 17 | @Component 18 | public class RetryExecutionAspect { 19 | 20 | private static final Logger LOGGER = LoggerFactory.getLogger("RetryLogger"); 21 | 22 | @Around("@annotation(com.bob.java.webapi.annotation.RetryExecution)") 23 | public Object doRetry(ProceedingJoinPoint point) throws Throwable { 24 | 25 | MethodSignature signature = (MethodSignature) point.getSignature(); 26 | Method method = signature.getMethod(); 27 | /*判断方法所属的类是否为接口*/ 28 | if (method.getDeclaringClass().isInterface()) { 29 | try { 30 | //获取实现方法 31 | method = point.getTarget().getClass() 32 | .getDeclaredMethod(point.getSignature().getName(), method.getParameterTypes()); 33 | } catch (final SecurityException exception) { 34 | LOGGER.error("方法重试失败, 该方法无法访问, class=" + method.getClass(), exception); 35 | throw exception; 36 | } catch (final NoSuchMethodException exception) { 37 | LOGGER.error("方法重试失败, 该方法不存在, class=" + method.getClass(), exception); 38 | throw exception; 39 | } 40 | } 41 | 42 | RetryExecution retryExecution = method.getAnnotation(RetryExecution.class); 43 | int retryAttempts = retryExecution.retryAttempts(); 44 | long sleepInterval = retryExecution.sleepInterval(); 45 | int allRetryAttempts = retryExecution.retryAttempts(); 46 | while (--retryAttempts >= 0) { 47 | try { 48 | if (retryAttempts < allRetryAttempts - 1) { 49 | LOGGER.info("重试Method: " + signature.toString()); 50 | } 51 | return point.proceed(); 52 | } catch (Throwable throwable) { 53 | LOGGER.error("重试操作出错, class=" + throwable.getClass()); 54 | LOGGER.debug("——————————方法重试操作---------"); 55 | LOGGER.debug("Method: " + signature.toString()); 56 | /*重试间隔时间*/ 57 | try { 58 | Thread.sleep(sleepInterval); 59 | } catch (InterruptedException e) { 60 | } 61 | } 62 | } 63 | return point.proceed(); 64 | } 65 | } -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/controller/ProtostufController.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.controller 2 | 3 | import javax.servlet.http.HttpServletRequest 4 | 5 | import org.springframework.beans.factory.annotation.Autowired 6 | import org.springframework.web.bind.annotation.{RequestBody, RequestMapping, RequestMethod, RestController} 7 | import org.springframework.web.servlet.mvc.method.annotation.{RequestMappingHandlerAdapter, RequestMappingHandlerMapping} 8 | 9 | import scala.collection.JavaConverters._ 10 | 11 | case class StubResponse(name: String, age: Int) 12 | 13 | class StubRequest(var name: String, var age: Int) { 14 | 15 | def this() { 16 | this("", 0) 17 | } 18 | } 19 | 20 | /** 21 | * Created by bob on 17/2/7. 22 | */ 23 | @RestController 24 | @RequestMapping(value = Array("protostuf/v1")) 25 | class ProtostufController { 26 | 27 | @Autowired 28 | private val requestMappingHandlerMapping: RequestMappingHandlerMapping = null 29 | 30 | @Autowired 31 | private val requestMappingHandlerAdapter: RequestMappingHandlerAdapter = null 32 | 33 | @RequestMapping(value = Array("/check"), method = Array(RequestMethod.GET)) 34 | def check() = { 35 | "OK" 36 | } 37 | 38 | /** 39 | * consumes属性限制请求头中的Content-Type值是application/x-protobuf才会处理 40 | * produces告诉客户端经过此处理后会返回类型是application/x-protobuf的数据,让其在Accept中指定此值 41 | * 42 | * @return 43 | */ 44 | @RequestMapping(value = Array("/stub"), 45 | method = Array(RequestMethod.POST), 46 | consumes = Array("application/x-protobuf"), 47 | produces = Array("application/x-protobuf") 48 | ) 49 | def stub(@RequestBody rq: StubRequest, request: HttpServletRequest): StubResponse = { 50 | println(s"age --> ${request.getParameter("ageage")}") 51 | println(s"name --> ${request.getParameter("name")}") 52 | new StubResponse(rq.name + "ab" + rq.name.length, rq.age + rq.name.length) 53 | } 54 | 55 | @RequestMapping(value = Array("/actions"), method = Array(RequestMethod.GET)) 56 | def listActions(): String = { 57 | val sb = new StringBuilder 58 | sb.append("URL").append("--").append("Class").append("--").append("Function").append('\n') 59 | requestMappingHandlerMapping.getHandlerMethods().asScala.foreach(x => { 60 | sb.append(x._1).append("--") 61 | .append(x._2.getMethod.getDeclaringClass).append("--") 62 | .append(x._2.getMethod.getName).append("\n") 63 | }) 64 | 65 | sb.toString() 66 | } 67 | 68 | @RequestMapping(value = Array("/mappers"), 69 | method = Array(RequestMethod.GET)) 70 | def listMappers(): String = { 71 | val sb = new StringBuilder 72 | sb.append("URL").append('\n') 73 | requestMappingHandlerAdapter.getMessageConverters.asScala.foreach(x => { 74 | sb.append(x.getClass.getSimpleName).append("\n") 75 | }) 76 | 77 | sb.toString() 78 | } 79 | } -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/ScalaApplication.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi 2 | 3 | import java.time.LocalDateTime 4 | 5 | import com.bob.java.webapi.handler.MdcPropagatingOnScheduleAction 6 | import com.bob.scala.webapi.controller.User 7 | import com.bob.scala.webapi.utils.CodeInvoke 8 | import com.fasterxml.jackson.databind.ObjectMapper 9 | import org.springframework.beans.factory.annotation.Autowired 10 | import org.springframework.beans.factory.support.{BeanDefinitionBuilder, DefaultListableBeanFactory} 11 | import org.springframework.boot.autoconfigure.SpringBootApplication 12 | import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration 13 | import org.springframework.boot.{CommandLineRunner, SpringApplication} 14 | import org.springframework.context.annotation.ComponentScan 15 | import org.springframework.scheduling.annotation.EnableAsync 16 | import org.springframework.stereotype.Controller 17 | import org.springframework.ui.Model 18 | import org.springframework.web.bind.annotation.{GetMapping, ResponseBody} 19 | import rx.plugins.RxJavaHooks 20 | import springfox.documentation.spring.web.json.JsonSerializer 21 | 22 | /** 23 | * Created by bob on 16/2/16. 24 | */ 25 | object ScalaApplication extends App { 26 | 27 | RxJavaHooks.setOnScheduleAction(new MdcPropagatingOnScheduleAction) 28 | println(CodeInvoke.invoke("1 + 1")) 29 | /** 30 | * args: _ *:此标注告诉编译器把args中的每个元素当作参数,而不是当作一个当一的参数传递 31 | */ 32 | private val cp = SpringApplication.run(classOf[SampleConfig], args: _ *) 33 | private val bdb = BeanDefinitionBuilder.rootBeanDefinition(classOf[ApplicationContextHolder]) 34 | cp.getBeanFactory.asInstanceOf[DefaultListableBeanFactory] 35 | .registerBeanDefinition("applicationContextHolder", bdb.getBeanDefinition) 36 | cp.getBean(classOf[ApplicationContextHolder]) 37 | } 38 | 39 | @SpringBootApplication(exclude = Array(classOf[ThymeleafAutoConfiguration])) 40 | @Controller 41 | @ComponentScan(value = Array( 42 | "com.bob.scala.*", "com.bob.java.webapi.*" 43 | )) 44 | @EnableAsync 45 | class SampleConfig extends CommandLineRunner { 46 | 47 | @Autowired 48 | var objectMapper: ObjectMapper = _ 49 | 50 | /** 51 | * 只有使用swagger的基础上才能导入此实例 52 | */ 53 | @Autowired 54 | val jsonSerializer: JsonSerializer = null 55 | 56 | @GetMapping(value = Array("/")) 57 | def index(model: Model): String = { 58 | model.addAttribute("now", LocalDateTime.now()) 59 | "index" 60 | } 61 | 62 | @GetMapping(value = Array("properties")) 63 | @ResponseBody 64 | def properties(): java.util.Properties = { 65 | System.getProperties() 66 | } 67 | 68 | override def run(args: String*): Unit = { 69 | val aUser = new User("c", 4, "a44", 4) 70 | println(objectMapper.writeValueAsString(aUser)) 71 | println(jsonSerializer.toJson(aUser).value()) 72 | val map = Map("message" -> "fucktest") 73 | println(objectMapper.writeValueAsString(map)) 74 | } 75 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/spextension/MDCDeferredResultProcessingInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.spextension; 2 | 3 | import com.bob.java.webapi.constant.MdcConstans; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.slf4j.MDC; 7 | import org.springframework.web.context.request.NativeWebRequest; 8 | import org.springframework.web.context.request.async.DeferredResult; 9 | import org.springframework.web.context.request.async.DeferredResultProcessingInterceptorAdapter; 10 | 11 | import java.util.Map; 12 | 13 | /** 14 | * 想将当前线程MDC值进递,在DeferredResutl中不能像Callable一样,添加拦截器几乎不起作用,几乎可以认定此类是个无用类 15 | * 如果想传递可以参照CallableController类那样将callable进行转换,或者利用SimpleAsyncTaskExecutor的execute方案来做 16 | *

17 | * 异步返回Callable跟DeferredResult区别 --> DeferredResult是由应用程序其它线程执行返回结果,而Callable是由TaskExecutor执行返回结果 18 | * Created by bob on 17/2/9. 19 | */ 20 | public class MDCDeferredResultProcessingInterceptor extends DeferredResultProcessingInterceptorAdapter { 21 | 22 | private static final Logger log = LoggerFactory.getLogger(MDCDeferredResultProcessingInterceptor.class); 23 | 24 | @Override 25 | public void beforeConcurrentHandling(NativeWebRequest request, DeferredResult deferredResult) throws Exception { 26 | log.info("beforeConcurrentHandling client id -> " + MDC.get(MdcConstans.MDC_ClientRequest_ID)); 27 | log.info("beforeConcurrentHandling remote ip -> " + MDC.get(MdcConstans.MDC_REMOTE_IP)); 28 | request.setAttribute("deferredresultmdcmap", MDC.getCopyOfContextMap(), -1); 29 | super.beforeConcurrentHandling(request, deferredResult); 30 | } 31 | 32 | @Override 33 | public void preProcess(NativeWebRequest request, DeferredResult deferredResult) throws Exception { 34 | // 经测试此线程跟beforeConcurrentHandling是同一个 35 | log.info("preProcess client id -> " + MDC.get(MdcConstans.MDC_ClientRequest_ID)); 36 | log.info("preProcess remote ip -> " + MDC.get(MdcConstans.MDC_REMOTE_IP)); 37 | super.preProcess(request, deferredResult); 38 | } 39 | 40 | @Override 41 | public void postProcess(NativeWebRequest request, DeferredResult deferredResult, Object concurrentResult) throws Exception { 42 | // 这是跟beforeConcurrentHandling不同的线程,并且已经可以知道deferredResult的result即入参值concurrentResult 43 | Map map = (Map) request.getAttribute("deferredresultmdcmap", -1); 44 | log.info("postProcess client id -> " + map.get(MdcConstans.MDC_ClientRequest_ID)); 45 | log.info("postProcess remote ip -> " + map.get(MdcConstans.MDC_REMOTE_IP)); 46 | MDC.setContextMap(map); 47 | super.postProcess(request, deferredResult, concurrentResult); 48 | } 49 | 50 | @Override 51 | public void afterCompletion(NativeWebRequest request, DeferredResult deferredResult) throws Exception { 52 | // 这又是另一个线程,所以这里相当于有三个线程 53 | log.info("afterCompletion client id -> " + MDC.get(MdcConstans.MDC_ClientRequest_ID)); 54 | log.info("afterCompletion remote ip -> " + MDC.get(MdcConstans.MDC_REMOTE_IP)); 55 | super.afterCompletion(request, deferredResult); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/controller/UserController.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.controller 2 | 3 | import javax.validation.Valid 4 | import javax.validation.constraints.{Max, Min, NotNull} 5 | 6 | import com.bob.scala.webapi.exception.{ServerException, ClientException} 7 | import io.swagger.annotations._ 8 | import org.springframework.hateoas.VndErrors 9 | import org.springframework.http.HttpStatus 10 | import org.springframework.web.bind.annotation._ 11 | 12 | import scala.collection.JavaConverters._ 13 | import scala.concurrent.{Promise, Future} 14 | 15 | @ApiModel("用户基本属性") 16 | case class User(@ApiModelProperty("姓名") name: String, 17 | @ApiModelProperty("年纪") age: Int, 18 | @ApiModelProperty("地址") address: String, 19 | @ApiModelProperty("性别") sex: Int) 20 | 21 | @ApiModel("添加用户基本信息参数") 22 | case class AddUserParam() { 23 | @ApiModelProperty("姓名") 24 | @NotNull 25 | var name: String = _; 26 | @ApiModelProperty("年纪") 27 | @Min(value = 1l, message = "年纪最少不能少于1") 28 | @Max(value = 100l, message = "年纪最大不能大于100") 29 | var age: Int = _; 30 | @ApiModelProperty("地址") 31 | @NotNull 32 | var address: String = _; 33 | @ApiModelProperty("性别") 34 | var sex: Int = _; 35 | } 36 | 37 | /** 38 | * Created by bob on 16/2/27. 39 | */ 40 | @RestController 41 | @RequestMapping(value = Array("users/v1")) 42 | @Api(value = "用户相关接口", description = "用户相关接口") 43 | class UserController { 44 | 45 | @RequestMapping(value = Array("lists"), method = Array(RequestMethod.GET)) 46 | @ApiOperation(value = "列出系统中所有用户信息") 47 | @ResponseStatus(HttpStatus.OK) 48 | @ApiResponses(Array( 49 | new ApiResponse(code = 401, message = "无权限操作", response = classOf[VndErrors]), 50 | new ApiResponse(code = 404, message = "没有处理器", response = classOf[VndErrors]), 51 | new ApiResponse(code = 204, message = "记录不存在", response = classOf[VndErrors]))) 52 | def lists(): java.util.List[User] = { 53 | val aUser = new User("c", 4, "a44", 4) 54 | val aList = List(new User("a", 1, "a11", 1), new User("b", 2, "b22", 2), new User("c", 3, "c33", 3)) 55 | aList.+:(aUser).asJava 56 | } 57 | 58 | /** 59 | * spring中全局出错处理器其实是由java触发的,那么此时需要通过注解来告诉会有哪些异常, 60 | * 要不然所有的ex类型都会成为UndeclaredThrowableException,就不能采用模式匹配 61 | */ 62 | @throws(classOf[ClientException]) 63 | @throws(classOf[ServerException]) 64 | @RequestMapping(value = Array("lists/{name}"), method = Array(RequestMethod.GET)) 65 | @ApiOperation("根据姓名查找用户") 66 | def findByName(@PathVariable("name") @ApiParam("用户姓名") name: String): User = { 67 | if (name == "abcde") { 68 | throw new ClientException("参数非法") 69 | } 70 | if (name == "abcd") { 71 | throw new IllegalArgumentException("参数出错") 72 | } 73 | User(name, 4, "a44", 4) 74 | } 75 | 76 | @RequestMapping(value = Array("lists"), method = Array(RequestMethod.POST)) 77 | @ApiOperation("创建一个用户") 78 | @throws(classOf[ServerException]) 79 | def createUser(@Valid @RequestBody param: AddUserParam): User = { 80 | if (param.name == "fuck") { 81 | throw ServerException(s"server error,${param.name}") 82 | } 83 | User(param.name, param.age, param.address, 84 | param.age) 85 | } 86 | } -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/controller/CallableController.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.controller 2 | 3 | import java.util.concurrent.{Callable, Executors, TimeUnit} 4 | 5 | import com.bob.java.webapi.spextension.MDCAwareCallable 6 | import com.bob.scala.webapi.service.HelperService 7 | import org.slf4j.{Logger, LoggerFactory, MDC} 8 | import org.springframework.beans.factory.annotation.Autowired 9 | import org.springframework.web.bind.annotation.{PathVariable, RequestMapping, RequestMethod, RestController} 10 | import org.springframework.web.context.request.async.{DeferredResult, WebAsyncTask} 11 | 12 | /** 13 | * 异步例子,返回callable,deferredresult,webasynctask 14 | * 15 | * Created by bob on 17/2/4. 16 | */ 17 | @RestController 18 | @RequestMapping(value = Array("callable/v1")) 19 | class CallableController { 20 | 21 | private val LOGGER: Logger = LoggerFactory.getLogger(getClass) 22 | 23 | @Autowired 24 | private val helperService: HelperService = null 25 | 26 | @RequestMapping(value = Array("rs/nocallable/{name}"), method = Array(RequestMethod.GET)) 27 | def nocallable(@PathVariable("name") name: String): String = { 28 | helperService.handlerInput(name) 29 | } 30 | 31 | @RequestMapping(value = Array("rs/callable/{name}"), method = Array(RequestMethod.GET)) 32 | def callable(@PathVariable("name") name: String): Callable[String] = { 33 | LOGGER.info(s"rs/callable/${name} begin to process}") 34 | new Callable[String] { 35 | def call() = { 36 | val r = helperService.handlerInput(name) 37 | LOGGER.info(s"rs/callable/${name} stop to process}") 38 | r 39 | } 40 | } 41 | } 42 | 43 | @RequestMapping(value = Array("rs/defferredrs/{name}"), method = Array(RequestMethod.GET)) 44 | def deferredResult(@PathVariable("name") name: String): DeferredResult[String] = { 45 | val differredrs = new DeferredResult[String](4000L) 46 | LOGGER.info(s"rs/defferredrs/${name} begin to process}") 47 | LongTimeAsyncCallService.makeRemoteCallAndUnknownWhenFinish(new LongTimeTaskCallback(name) { 48 | def callback(result: Any) = { 49 | LOGGER.info(s"rs/defferredrs/${name} stop to process}") 50 | differredrs.setResult(result.toString) 51 | } 52 | }) 53 | differredrs.onTimeout(new Runnable { 54 | def run() = differredrs.setResult(s"${name} is timeout") 55 | }) 56 | differredrs 57 | } 58 | 59 | @RequestMapping(value = Array("rs/webasynctask/{name}"), method = Array(RequestMethod.GET)) 60 | def webAsyncTask(@PathVariable("name") name: String): WebAsyncTask[String] = { 61 | LOGGER.info("/rs/webasynctask begin to process") 62 | new WebAsyncTask[String](new Callable[String] { 63 | def call() = { 64 | val r = helperService.handlerInput(name) 65 | LOGGER.info("rs/webasynctask stop to process") 66 | r 67 | } 68 | }) 69 | } 70 | 71 | abstract class LongTimeTaskCallback(val parm: Any) { 72 | def callback(result: Any) 73 | } 74 | 75 | object LongTimeAsyncCallService { 76 | private val scheduler = Executors.newScheduledThreadPool(4) 77 | 78 | def makeRemoteCallAndUnknownWhenFinish(callback: LongTimeTaskCallback) { 79 | scheduler.schedule(MDCAwareCallable.wrap(new Runnable { 80 | def run() = { 81 | callback.callback(s"${helperService.handlerInput(callback.parm.toString)} is done") 82 | } 83 | }, MDC.getCopyOfContextMap), 1, TimeUnit.SECONDS) 84 | } 85 | } 86 | 87 | } -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/config/SwaggerConfig.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.config 2 | 3 | import javax.annotation.PostConstruct 4 | 5 | import com.fasterxml.jackson.core.JsonGenerator 6 | import com.fasterxml.jackson.core.json.PackageVersion 7 | import com.fasterxml.jackson.databind.module.SimpleModule 8 | import com.fasterxml.jackson.databind.{JsonSerializer, ObjectMapper, SerializerProvider} 9 | import com.fasterxml.jackson.module.scala.DefaultScalaModule 10 | import org.springframework.beans.factory.annotation.Value 11 | import org.springframework.context.ApplicationListener 12 | import org.springframework.context.annotation.{Bean, Scope} 13 | import org.springframework.web.context.request.async.DeferredResult 14 | import springfox.documentation.builders.ApiInfoBuilder 15 | import springfox.documentation.builders.PathSelectors.regex 16 | import springfox.documentation.schema.configuration.ObjectMapperConfigured 17 | import springfox.documentation.service.ApiInfo 18 | import springfox.documentation.spi.DocumentationType 19 | import springfox.documentation.spring.web.plugins.Docket 20 | import springfox.documentation.swagger2.annotations.EnableSwagger2 21 | 22 | /** 23 | * Created by bob on 16/2/27. 24 | */ 25 | @EnableSwagger2 26 | class SwaggerConfig { 27 | 28 | @Value("${swagger.ui.enable}") 29 | val swagger_ui_enable: Boolean = false 30 | 31 | @Value("${swagger.ui.enable}") 32 | var swagger_ui_enable_string: String = _ 33 | 34 | // @Autowired 35 | // val objectMapper: ObjectMapper = null 36 | 37 | /** 38 | * 用户接口列表 39 | * 40 | * @return 41 | */ 42 | @Bean 43 | @Scope("singletion") 44 | def userDocketFactory: Docket = { 45 | val docket = new Docket(DocumentationType.SWAGGER_2) 46 | .apiInfo(apiInfo) 47 | .groupName("userInterface") 48 | .select() 49 | .paths(regex("/users.*")) 50 | .build() 51 | .useDefaultResponseMessages(false) 52 | docket.enable(swagger_ui_enable) 53 | } 54 | 55 | def apiInfo: ApiInfo = { 56 | new ApiInfoBuilder() 57 | .title("Spring Boot Using Scala With Swagger") 58 | .description("User Interface API") 59 | .contact("sevenz_da_best@hotmail.com") 60 | .license("Apache License, Version 2.0") 61 | .version("1.0") 62 | .build() 63 | } 64 | 65 | @PostConstruct 66 | def initObject(): Unit = { 67 | // objectMapper.registerModule(DefaultScalaModule) 68 | } 69 | 70 | /** 71 | * 如果采用注入objectMapper,然后在initObject中添加对scala的处理,那样在帮助文档中至少目前不会显示@ApiModelProperty的注解, 72 | * 采用事件触发添加会显示,但测试下来发现只显示Response的,如果PostBody则又会忽略,感觉这块跟scala结合的还不是很好, 73 | * 也有可能跟scala的类定义有关,还需仔细看下 74 | * 75 | * @return 76 | */ 77 | @Bean 78 | def objectMapperInitializer = new ApplicationListener[ObjectMapperConfigured] { 79 | def onApplicationEvent(event: ObjectMapperConfigured) = { 80 | event.getObjectMapper.registerModule(DefaultScalaModule) 81 | 82 | val newModule = new SimpleModule("UTCDateDeserializer", PackageVersion.VERSION) 83 | newModule.addSerializer(classOf[DeferredResult[_]], new DeferredResultSerializer(event.getObjectMapper)) 84 | event.getObjectMapper.registerModule(newModule) 85 | } 86 | } 87 | } 88 | 89 | class DeferredResultSerializer(objectMapper: ObjectMapper) extends JsonSerializer[DeferredResult[_]] { 90 | 91 | override def serialize(value: DeferredResult[_], gen: JsonGenerator, serializers: SerializerProvider) = { 92 | gen.writeString(objectMapper.writeValueAsString(value.getResult)) 93 | } 94 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/filter/MDCFilter.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.filter; 2 | 3 | import com.bob.java.webapi.constant.AppConstants; 4 | import com.bob.java.webapi.constant.MdcConstans; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.slf4j.MDC; 8 | import org.springframework.util.StringUtils; 9 | import org.springframework.web.filter.OncePerRequestFilter; 10 | import org.springframework.web.util.UrlPathHelper; 11 | 12 | import javax.servlet.FilterChain; 13 | import javax.servlet.ServletException; 14 | import javax.servlet.http.HttpServletRequest; 15 | import javax.servlet.http.HttpServletResponse; 16 | import java.io.IOException; 17 | import java.util.UUID; 18 | 19 | /** 20 | * Created by bob on 17/2/6. 21 | */ 22 | public class MDCFilter extends OncePerRequestFilter { 23 | 24 | private final Logger log = LoggerFactory.getLogger(MDCFilter.class); 25 | 26 | private final UrlPathHelper urlPathHelper = new UrlPathHelper(); 27 | 28 | @Override 29 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { 30 | 31 | String path = urlPathHelper.getPathWithinApplication(request); 32 | if (path.contains("webjars") || path.contains("swagger") 33 | || path.contains("api-docs") || path.contains("configuration") 34 | || path.contains("images") || path.contains("favicon.ico")) { 35 | filterChain.doFilter(request, response); 36 | return; 37 | } 38 | 39 | handlerRemoteIp(request); 40 | handlerClientRequestId(request); 41 | 42 | try { 43 | log.info(path + " -> 开始客户端请求ip -> " + MDC.get(MdcConstans.MDC_REMOTE_IP) + " 标识符是 -> " + MDC.get(MdcConstans.MDC_ClientRequest_ID)); 44 | filterChain.doFilter(request, response); 45 | } finally { 46 | try { 47 | log.info(path + " -> 结束客户端请求ip -> " + MDC.get(MdcConstans.MDC_REMOTE_IP) + " 标识符是 -> " + MDC.get(MdcConstans.MDC_ClientRequest_ID)); 48 | MDC.clear(); 49 | } finally { 50 | MDC.clear(); 51 | } 52 | } 53 | } 54 | 55 | private void handlerClientRequestId(HttpServletRequest request) { 56 | String clientRequestId = request.getHeader(AppConstants.X_Client_Request_Id); 57 | if (StringUtils.isEmpty(clientRequestId)) { 58 | clientRequestId = UUID.randomUUID().toString(); 59 | log.debug("无法从http头获得请求标识, 自己生成一个: " + clientRequestId); 60 | } 61 | MDC.put(MdcConstans.MDC_ClientRequest_ID, clientRequestId); 62 | } 63 | 64 | private void handlerRemoteIp(HttpServletRequest request) { 65 | String remoteIp = request.getHeader(AppConstants.X_FORWARDED_FOR_HEADER); 66 | if (StringUtils.isEmpty(remoteIp)) { 67 | remoteIp = request.getHeader(AppConstants.X_REMOTE_IP_HEADER); 68 | if (StringUtils.isEmpty(remoteIp)) { 69 | remoteIp = request.getRemoteAddr(); 70 | if (StringUtils.isEmpty(remoteIp)) { 71 | log.debug("无法从http头获得remote_ip, 使用默认值127.0.0.1."); 72 | MDC.put(MdcConstans.MDC_REMOTE_IP, "127.0.0.1"); 73 | return; 74 | } 75 | } 76 | } 77 | 78 | if (remoteIp.contains(",")) { 79 | remoteIp = StringUtils.split(remoteIp, ",")[0].trim(); 80 | } 81 | MDC.put(MdcConstans.MDC_REMOTE_IP, remoteIp); 82 | } 83 | } -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/config/SpringConfig.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.config 2 | 3 | import java.io.IOException 4 | import javax.servlet.http.{HttpServletRequest, HttpServletResponse} 5 | 6 | import com.bob.scala.webapi.exception.{ClientException, ServerException} 7 | import com.bob.scala.webapi.utils.LoggerObject 8 | import com.fasterxml.jackson.databind.ObjectMapper 9 | import org.springframework.beans.factory.annotation.Autowired 10 | import org.springframework.context.annotation.Import 11 | import org.springframework.hateoas.VndErrors 12 | import org.springframework.http.{HttpHeaders, HttpStatus, ResponseEntity} 13 | import org.springframework.web.bind.annotation.{ControllerAdvice, ExceptionHandler, ResponseBody, RestController} 14 | import org.springframework.web.context.request.WebRequest 15 | import org.springframework.web.servlet.mvc.method.annotation.{AbstractJsonpResponseBodyAdvice, ResponseEntityExceptionHandler} 16 | 17 | /** 18 | * Created by bob on 16/2/29. 19 | */ 20 | @Import(value = Array(classOf[RestErrorHandler], classOf[JsonpAdvice])) 21 | class SpringConfig { 22 | } 23 | 24 | @ControllerAdvice(annotations = Array(classOf[RestController])) 25 | class JsonpAdvice extends AbstractJsonpResponseBodyAdvice("callback", "jsonp") { 26 | 27 | } 28 | 29 | /** 30 | * 全局统一出错处理 31 | */ 32 | @ControllerAdvice(annotations = Array(classOf[RestController])) 33 | class RestErrorHandler extends ResponseEntityExceptionHandler with LoggerObject { 34 | 35 | @Autowired 36 | var objectMapper: ObjectMapper = null 37 | 38 | @ExceptionHandler(value = Array(classOf[Exception])) 39 | @ResponseBody 40 | @throws(classOf[IOException]) 41 | def handleRequests(request: HttpServletRequest, response: HttpServletResponse, 42 | ex: Exception): ResponseEntity[VndErrors] = { 43 | 44 | logError(ex, request) 45 | 46 | val message = if (ex.getMessage == null) "null" else ex.getMessage 47 | val vndErrors: VndErrors = new VndErrors(ex.getClass.getSimpleName, message) 48 | ex match { 49 | case ClientException(err, state) => response.setStatus(state) 50 | case ServerException(err, state) => response.setStatus(state) 51 | case _ => response.setStatus(500) 52 | } 53 | 54 | new ResponseEntity[VndErrors](vndErrors, HttpStatus.valueOf(response.getStatus())) 55 | } 56 | 57 | /** 58 | * 重载方法加入日志 59 | * 60 | * @param ex 61 | * @param body 62 | * @param headers 63 | * @param status 64 | * @param request 65 | * @return 66 | */ 67 | override def handleExceptionInternal(ex: Exception, body: scala.Any, 68 | headers: HttpHeaders, status: HttpStatus, 69 | request: WebRequest): ResponseEntity[AnyRef] = { 70 | logError(ex) 71 | super.handleExceptionInternal(ex, body, headers, status, request) 72 | } 73 | 74 | def logError(ex: Exception): Unit = { 75 | try { 76 | val map = Map("message" -> ex.getMessage) 77 | LOGGER.error(objectMapper.writeValueAsString(map), ex) 78 | } catch { 79 | case e: Exception => {} 80 | } 81 | } 82 | 83 | def logError(ex: Exception, request: HttpServletRequest): Unit = { 84 | try { 85 | val map = Map("message" -> ex.getMessage, 86 | "from" -> request.getRemoteAddr, 87 | "path" -> (if (request.getQueryString == null) request.getRequestURI else request.getRequestURI + "?" + request.getQueryString)); 88 | LOGGER.error(objectMapper.writeValueAsString(map), ex) 89 | } catch { 90 | case e: Exception => {} 91 | } 92 | } 93 | } -------------------------------------------------------------------------------- /webapi/src/test/scala/com/bob/scala/webapi/ProtostufControllerTest.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi 2 | 3 | import com.bob.java.webapi.utils.ProtostufUtils 4 | import com.bob.scala.webapi.controller.{ProtostufController, StubRequest, StubResponse} 5 | import io.protostuff.ProtobufIOUtil 6 | import io.protostuff.runtime.RuntimeSchema 7 | import org.junit.Test 8 | import org.junit.runner.RunWith 9 | import org.springframework.beans.factory.annotation.Autowired 10 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest 11 | import org.springframework.boot.test.web.client.TestRestTemplate 12 | import org.springframework.http.MediaType 13 | import org.springframework.test.context.junit4.SpringRunner 14 | import org.springframework.test.web.servlet.request.MockMvcRequestBuilders 15 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers 16 | import org.springframework.test.web.servlet.{MockMvc, MvcResult, ResultMatcher} 17 | 18 | import scala.collection.JavaConverters._ 19 | 20 | /** 21 | * Created by bob on 17/2/7. 22 | */ 23 | @RunWith(classOf[SpringRunner]) 24 | @WebMvcTest(controllers = Array(classOf[ProtostufController])) 25 | class ProtostufControllerTest { 26 | 27 | @Autowired 28 | private val mvc: MockMvc = null 29 | 30 | private val template: TestRestTemplate = new TestRestTemplate 31 | 32 | @Test 33 | def testCheck(): Unit = { 34 | val c = MockMvcResultMatchers.content().string("\"OK\"") 35 | this.mvc.perform(MockMvcRequestBuilders.get("/protostuf/v1/check")) 36 | .andExpect(MockMvcResultMatchers.status().isOk()) 37 | .andExpect(c) 38 | } 39 | 40 | @Test 41 | def testStub(): Unit = { 42 | 43 | val rq = new StubRequest("fucku", 1) 44 | val byte = ProtostufUtils.serialize(rq) 45 | 46 | this.mvc.perform(MockMvcRequestBuilders 47 | .post("/protostuf/v1/stub?name=123&age=12") 48 | .contentType(new MediaType("application", "x-protobuf")) 49 | .accept(new MediaType("application", "x-protobuf")) 50 | .content(byte)) 51 | .andExpect(MockMvcResultMatchers.status().isOk()) 52 | .andExpect(new ResultMatcher() { 53 | def `match`(result: MvcResult) { 54 | result.getResponse.getHeaderNames.asScala.foreach(x => { 55 | println(s"${x} --> ${result.getResponse.getHeaders(x).asScala.mkString(",")}") 56 | }) 57 | 58 | if (result.getResponse.getContentType == "application/json;charset=UTF-8") { 59 | println(result.getResponse.getContentAsString) 60 | } else { 61 | val byteResult: Array[Byte] = result.getResponse.getContentAsByteArray 62 | val schema = RuntimeSchema.getSchema(classOf[StubResponse]) 63 | val stubResponse: StubResponse = schema.newMessage() 64 | ProtobufIOUtil.mergeFrom(byteResult, stubResponse, schema) 65 | println(stubResponse) 66 | } 67 | } 68 | }) 69 | } 70 | 71 | @Test 72 | def testListMappers(): Unit = { 73 | this.mvc.perform(MockMvcRequestBuilders 74 | .get("/protostuf/v1/mappers")) 75 | .andExpect(MockMvcResultMatchers.status().isOk()) 76 | .andExpect(new ResultMatcher() { 77 | def `match`(result: MvcResult) { 78 | // val byteResult: Array[Byte] = result.getResponse.getContentAsByteArray 79 | // val schema = RuntimeSchema.getSchema(classOf[String]) 80 | // val stubResponse: String = schema.newMessage() 81 | // ProtobufIOUtil.mergeFrom(byteResult, stubResponse, schema) 82 | // println(stubResponse) 83 | 84 | val l = result.getResponse.getContentAsString 85 | println(l) 86 | } 87 | }) 88 | } 89 | } -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/utils/DistributeLock.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.utils 2 | 3 | import java.util.concurrent.TimeUnit 4 | 5 | import redis.clients.jedis.JedisCluster 6 | 7 | /** 8 | * Created by bob on 16/3/21. 9 | */ 10 | trait DistributeLock { 11 | 12 | /** 13 | * 默认锁有效时间(单位毫秒) 14 | */ 15 | val DEFAULT_LOCK_EXPIRE_TIME = 60000L 16 | 17 | /** 18 | * 默认睡眠时间(单位毫秒) 19 | */ 20 | val DEFAULT_SLEEP_TIME = 100L 21 | 22 | /** 23 | * 尝试锁 24 | * 25 | * @param lock 锁的键 26 | * @param requestTimeout 请求超时 ms 27 | * @return 如果锁成功,则返回true;否则返回false 28 | */ 29 | def tryLock(lock: String, requestTimeout: Long): Boolean 30 | 31 | /** 32 | * 尝试锁 33 | * @param lock 锁的键 34 | * @param lockExpireTime 锁有效期 ms 35 | * @param requestTimeout 请求超时 ms 36 | * @return 如果锁成功,则返回true;否则返回false 37 | */ 38 | def tryLock(lock: String, lockExpireTime: Long, requestTimeout: Long): Boolean 39 | 40 | /** 41 | * 解锁 42 | * @param lock 锁的键 43 | */ 44 | def unlock(lock: String): Unit 45 | } 46 | 47 | /** 48 | * 使用redis做为分布式锁 49 | */ 50 | class RedisDistributeLock(jedisCluster: JedisCluster) extends DistributeLock { 51 | 52 | import java.lang.{Long => JLong} 53 | 54 | /** 55 | * 尝试锁 56 | * 57 | * @param lock 锁的键 58 | * @param requestTimeout 请求超时 ms 59 | * @return 如果锁成功,则返回true;否则返回false 60 | */ 61 | override def tryLock(lock: String, requestTimeout: Long): Boolean = { 62 | this.tryLock(lock, DEFAULT_LOCK_EXPIRE_TIME, requestTimeout) 63 | } 64 | 65 | /** 66 | * 尝试锁 67 | * @param lock 锁的键 68 | * @param lockExpireTime 锁有效期 ms 69 | * @param requestTimeout 请求超时 ms 70 | * @return 如果锁成功,则返回true;否则返回false 71 | */ 72 | override def tryLock(lock: String, lockExpireTime: Long, requestTimeout: Long): Boolean = { 73 | require(lock != null && lock.trim.length > 0, "lock invalid") 74 | require(lockExpireTime > 0) 75 | require(requestTimeout > 0) 76 | 77 | var requireTimeout = requestTimeout 78 | while (requireTimeout > 0) { 79 | val expire: String = String.valueOf(System.currentTimeMillis + lockExpireTime + 1) 80 | val result: Long = jedisCluster.setnx(lock, expire) 81 | if (result > 0) { 82 | // 目前没有线程占用此锁 83 | jedisCluster.expire(lock, JLong.valueOf(lockExpireTime / 1000).intValue) 84 | return true 85 | } 86 | val currentValue: String = jedisCluster.get(lock) 87 | if (currentValue != null) { 88 | if (JLong.parseLong(currentValue) < System.currentTimeMillis) { 89 | val oldValue: String = jedisCluster.getSet(lock, expire) 90 | if (oldValue == null || (oldValue != null && (oldValue == currentValue))) { 91 | jedisCluster.expire(lock, JLong.valueOf(lockExpireTime / 1000).intValue) 92 | return true 93 | } 94 | } 95 | } 96 | var sleepTime: Long = 0 97 | if (requestTimeout > DEFAULT_SLEEP_TIME) { 98 | sleepTime = DEFAULT_SLEEP_TIME 99 | requireTimeout -= DEFAULT_SLEEP_TIME 100 | } 101 | else { 102 | sleepTime = requestTimeout 103 | requireTimeout = 0 104 | } 105 | try { 106 | TimeUnit.MILLISECONDS.sleep(sleepTime) 107 | } 108 | catch { 109 | case e: InterruptedException => { 110 | 111 | } 112 | } 113 | } 114 | false 115 | } 116 | 117 | /** 118 | * 解锁 119 | * @param lock 锁的键 120 | */ 121 | override def unlock(lock: String): Unit = { 122 | val value: String = jedisCluster.get(lock) 123 | if (value != null && JLong.parseLong(value) > System.currentTimeMillis) { 124 | jedisCluster.del(lock) 125 | } 126 | } 127 | } -------------------------------------------------------------------------------- /webapi/src/main/scala/com/bob/scala/webapi/config/WebConfig.scala: -------------------------------------------------------------------------------- 1 | package com.bob.scala.webapi.config 2 | 3 | import java.util 4 | 5 | import com.bob.java.webapi.converter.ProtostuffHttpMessageConverter 6 | import com.bob.java.webapi.filter.MDCFilter 7 | import com.bob.java.webapi.handler.ObservableReturnValueHandler 8 | import com.bob.java.webapi.spextension.{MDCCallableProcessingInterceptor, MDCDeferredResultProcessingInterceptor, MDCSimpleAsyncTaskExecutor} 9 | import com.fasterxml.jackson.annotation.JsonInclude 10 | import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper, SerializationFeature} 11 | import org.springframework.amqp.support.converter.SimpleMessageConverter 12 | import org.springframework.beans.factory.annotation.Autowired 13 | import org.springframework.context.MessageSource 14 | import org.springframework.context.annotation.{Bean, Configuration, Import} 15 | import org.springframework.context.support.ResourceBundleMessageSource 16 | import org.springframework.core.env.Environment 17 | import org.springframework.core.task.SimpleAsyncTaskExecutor 18 | import org.springframework.http.converter.HttpMessageConverter 19 | import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter 20 | import org.springframework.web.method.support.HandlerMethodReturnValueHandler 21 | import org.springframework.web.servlet.config.annotation.{AsyncSupportConfigurer, WebMvcConfigurerAdapter} 22 | 23 | /** 24 | * Created by bob on 16/2/27. 25 | */ 26 | @Configuration 27 | @Import(value = Array(classOf[SwaggerConfig], classOf[SpringConfig])) 28 | class WebConfig extends WebMvcConfigurerAdapter { 29 | 30 | @Autowired 31 | private val environment: Environment = null 32 | 33 | @Autowired 34 | private val objectMapper: ObjectMapper = null 35 | 36 | @Bean 37 | def simpleObjectMapper(): SimpleMessageConverter = { 38 | new SimpleMessageConverter 39 | } 40 | 41 | @Bean def simpleAsyncTaskExecutor: SimpleAsyncTaskExecutor = new MDCSimpleAsyncTaskExecutor 42 | 43 | override def configureAsyncSupport(configurer: AsyncSupportConfigurer) = { 44 | configurer.setTaskExecutor(simpleAsyncTaskExecutor) 45 | configurer.setDefaultTimeout(4000L) 46 | // configurer.registerCallableInterceptors(mdcCallableProcessingInterceptor()) 47 | configurer.registerDeferredResultInterceptors(mdcDeferredResultProcessingInterceptor()) 48 | } 49 | 50 | @Bean 51 | def mdcCallableProcessingInterceptor(): MDCCallableProcessingInterceptor = { 52 | new MDCCallableProcessingInterceptor() 53 | } 54 | 55 | @Bean 56 | def mdcDeferredResultProcessingInterceptor(): MDCDeferredResultProcessingInterceptor = { 57 | new MDCDeferredResultProcessingInterceptor() 58 | } 59 | 60 | @Bean 61 | def protostuffHttpMessageConverte(): ProtostuffHttpMessageConverter = { 62 | new ProtostuffHttpMessageConverter() 63 | } 64 | 65 | override def configureMessageConverters(converters: util.List[HttpMessageConverter[_]]) = { 66 | val converter = new MappingJackson2HttpMessageConverter() 67 | val objectMapper = new ObjectMapper() 68 | objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true) 69 | objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) 70 | objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) 71 | objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL) 72 | converter.setObjectMapper(objectMapper) 73 | converters.add(converter) 74 | } 75 | 76 | @Bean 77 | def mdcFilter(): MDCFilter = { 78 | new MDCFilter 79 | } 80 | 81 | override def addReturnValueHandlers(returnValueHandlers: util.List[HandlerMethodReturnValueHandler]) = { 82 | super.addReturnValueHandlers(returnValueHandlers) 83 | returnValueHandlers.add(new ObservableReturnValueHandler) 84 | } 85 | 86 | // private val MESSAGESOURCE_BASENAME = "message.source.basename" 87 | // private val MESSAGESOURCE_USE_CODE_AS_DEFAULT_MESSAGE = "message.source.use.code.as.default.message" 88 | 89 | @Bean 90 | def messageSource(): MessageSource = { 91 | val messageSource = new ResourceBundleMessageSource() 92 | // messageSource.setBasename(environment.getRequiredProperty(MESSAGESOURCE_BASENAME)) 93 | // messageSource.setUseCodeAsDefaultMessage( 94 | // java.lang.Boolean.parseBoolean(environment.getRequiredProperty(MESSAGESOURCE_USE_CODE_AS_DEFAULT_MESSAGE))) 95 | messageSource 96 | } 97 | 98 | } -------------------------------------------------------------------------------- /webapi/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | bootspring-scala-parent 7 | org.bob.scala 8 | 0.0.1-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | webapi 13 | 14 | 15 | 16 | 17 | com.fasterxml.jackson.module 18 | jackson-module-scala_2.11 19 | 2.8.6 20 | 21 | 22 | 23 | redis.clients 24 | jedis 25 | 26 | 27 | 28 | io.protostuff 29 | protostuff-core 30 | 1.5.2 31 | 32 | 33 | io.protostuff 34 | protostuff-runtime 35 | 1.5.2 36 | 37 | 38 | 39 | org.xerial.snappy 40 | snappy-java 41 | 1.1.3-M2 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | commons-io 52 | commons-io 53 | 2.5 54 | 55 | 56 | 57 | org.webjars 58 | bootstrap 59 | 3.3.6 60 | 61 | 62 | org.webjars 63 | jquery 64 | 2.2.1 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | springboot-scala-withswagger 77 | 78 | 108 | 109 | 110 | -------------------------------------------------------------------------------- /webapi/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | %d{yyyy-MM-dd HH:mm:ss SSS} [%thread] [%X{tid}] %-5level %logger{36} - %msg%n 14 | 15 | UTF-8 16 | 17 | 18 | 19 | 20 | 21 | ${LOG_HOME}/${SCALATOULLOGFILENAME}-%d{yyyy-MM-dd}.%i.log 22 | 24 | 25 | 200 MB 26 | 27 | 28 | 29 | 30 | DEBUG 31 | 32 | 33 | true 34 | 35 | 36 | 37 | 39 | 40 | 41 | %d{yyyy-MM-dd HH:mm:ss SSS} [%thread] [%X{tid}] %-5level %logger{36} - %msg%n 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | %d{yyyy-MM-dd HH:mm:ss SSS} [%thread] [%X{tid}] %-5level %logger{36} - %msg%n 51 | 52 | UTF-8 53 | 54 | 55 | 56 | 57 | 58 | ${LOG_HOME}/${SCALATOULLOGFILENAME}_requestlog-%d{yyyy-MM-dd}.%i.log 59 | 61 | 62 | 200 MB 63 | 64 | 65 | 66 | 67 | DEBUG 68 | 69 | 70 | true 71 | 72 | 73 | 75 | 76 | 77 | 78 | %d{yyyy-MM-dd HH:mm:ss SSS} [%thread] %-5level %logger{36} - %msg%n 79 | 80 | UTF-8 81 | 82 | 83 | 84 | 85 | 86 | /var/www/logs/retry-%d{yyyy-MM-dd}.%i.log 87 | 88 | 7 89 | 91 | 92 | 200 MB 93 | 94 | 95 | 96 | 97 | DEBUG 98 | 99 | true 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/converter/ProtostuffHttpMessageConverter.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.converter; 2 | 3 | import com.google.common.base.Stopwatch; 4 | import io.protostuff.LinkedBuffer; 5 | import io.protostuff.ProtobufIOUtil; 6 | import io.protostuff.Schema; 7 | import io.protostuff.runtime.RuntimeSchema; 8 | import org.apache.commons.io.IOUtils; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | import org.springframework.http.HttpInputMessage; 12 | import org.springframework.http.HttpOutputMessage; 13 | import org.springframework.http.MediaType; 14 | import org.springframework.http.converter.AbstractHttpMessageConverter; 15 | import org.springframework.http.converter.HttpMessageNotReadableException; 16 | import org.springframework.http.converter.HttpMessageNotWritableException; 17 | import org.xerial.snappy.SnappyOutputStream; 18 | 19 | import java.io.IOException; 20 | import java.io.InputStream; 21 | import java.io.OutputStream; 22 | import java.nio.charset.Charset; 23 | import java.util.Map; 24 | import java.util.concurrent.ConcurrentHashMap; 25 | import java.util.zip.GZIPOutputStream; 26 | 27 | /** 28 | * Created by bob on 17/1/17. 29 | */ 30 | public class ProtostuffHttpMessageConverter extends AbstractHttpMessageConverter { 31 | 32 | private final Logger logger = LoggerFactory.getLogger(ProtostuffHttpMessageConverter.class); 33 | 34 | public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); 35 | public static final MediaType MEDIA_TYPE = new MediaType("application", "x-protobuf", DEFAULT_CHARSET); 36 | public static final MediaType MEDIA_TYPE_GZIP = new MediaType("application", "x-protobuf-gzip", DEFAULT_CHARSET); 37 | public static final MediaType MEDIA_TYPE_SNAPPY = new MediaType("application", "x-protobuf-snappy", DEFAULT_CHARSET); 38 | public static final String X_PROTOBUF_SCHEMA_HEADER = "X-Protobuf-Schema"; 39 | public static final String X_PROTOBUF_MESSAGE_HEADER = "X-Protobuf-Message"; 40 | 41 | public ProtostuffHttpMessageConverter() { 42 | super(MEDIA_TYPE, MEDIA_TYPE_GZIP, MEDIA_TYPE_SNAPPY); 43 | } 44 | 45 | @Override 46 | public boolean canRead(Class clazz, MediaType mediaType) { 47 | if (mediaType == null) { 48 | return false; 49 | } 50 | return mediaType.isCompatibleWith(MEDIA_TYPE); 51 | } 52 | 53 | @Override 54 | public boolean canWrite(Class clazz, MediaType mediaType) { 55 | if (mediaType == null) { 56 | return false; 57 | } 58 | return mediaType.isCompatibleWith(MEDIA_TYPE); 59 | } 60 | 61 | @Override 62 | protected boolean supports(Class clazz) { 63 | // Should not be called, since we override canRead/canWrite. 64 | throw new UnsupportedOperationException(); 65 | } 66 | 67 | private static Map, Schema> cachedSchema = new ConcurrentHashMap<>(); 68 | 69 | @SuppressWarnings("unchecked") 70 | private static Schema getSchema(final Class clasz) { 71 | Schema schema = (Schema) cachedSchema.get(clasz); 72 | if (schema == null) { 73 | schema = RuntimeSchema.createFrom(clasz); 74 | if (schema != null) { 75 | cachedSchema.put(clasz, schema); 76 | } 77 | } 78 | return schema; 79 | } 80 | 81 | @Override 82 | protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { 83 | 84 | MediaType contentType = inputMessage.getHeaders().getContentType(); 85 | if (MEDIA_TYPE.isCompatibleWith(contentType)) { 86 | final Schema schema = getSchema(clazz); 87 | final Object value = schema.newMessage(); 88 | 89 | try (final InputStream stream = inputMessage.getBody()) { 90 | ProtobufIOUtil.mergeFrom(stream, value, (Schema) schema); 91 | return value; 92 | } 93 | } 94 | 95 | throw new HttpMessageNotReadableException( 96 | "Unrecognized HTTP media type " + inputMessage.getHeaders().getContentType().getType() + "."); 97 | } 98 | 99 | @Override 100 | protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { 101 | 102 | logger.info("Current type: {}", outputMessage.getHeaders().getContentType()); 103 | Stopwatch stopwatch = Stopwatch.createStarted(); 104 | OutputStream stream = null; 105 | 106 | try { 107 | if (MEDIA_TYPE.isCompatibleWith(outputMessage.getHeaders().getContentType())) { 108 | outputMessage.getHeaders().set(X_PROTOBUF_SCHEMA_HEADER, o.getClass().getSimpleName()); 109 | outputMessage.getHeaders().set(X_PROTOBUF_MESSAGE_HEADER, o.getClass().getName()); 110 | stream = outputMessage.getBody(); 111 | } else if (MEDIA_TYPE_GZIP.isCompatibleWith(outputMessage.getHeaders().getContentType())) { 112 | stream = new GZIPOutputStream(stream); 113 | } else if (MEDIA_TYPE_SNAPPY.isCompatibleWith(outputMessage.getHeaders().getContentType())) { 114 | stream = new SnappyOutputStream(stream); 115 | } else { 116 | throw new HttpMessageNotWritableException( 117 | "Unrecognized HTTP media type " + outputMessage.getHeaders().getContentType().getType() + "."); 118 | } 119 | 120 | ProtobufIOUtil.writeTo(stream, o, getSchema((Class) o.getClass()), 121 | LinkedBuffer.allocate()); 122 | stream.flush(); 123 | } finally { 124 | IOUtils.closeQuietly(stream); 125 | } 126 | 127 | logger.info("Output spend {}", stopwatch.toString()); 128 | } 129 | } -------------------------------------------------------------------------------- /webapi/src/main/java/com/bob/java/webapi/config/Thymeleaf3Config.java: -------------------------------------------------------------------------------- 1 | package com.bob.java.webapi.config; 2 | 3 | import nz.net.ultraq.thymeleaf.LayoutDialect; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.autoconfigure.AutoConfigureAfter; 6 | import org.springframework.boot.autoconfigure.condition.*; 7 | import org.springframework.boot.autoconfigure.web.ConditionalOnEnabledResourceChain; 8 | import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; 9 | import org.springframework.context.ApplicationContext; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | import org.springframework.core.Ordered; 13 | import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter; 14 | import org.thymeleaf.Thymeleaf; 15 | import org.thymeleaf.dialect.IDialect; 16 | import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect; 17 | import org.thymeleaf.spring4.SpringTemplateEngine; 18 | import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; 19 | import org.thymeleaf.spring4.view.ThymeleafViewResolver; 20 | import org.thymeleaf.templatemode.TemplateMode; 21 | import org.thymeleaf.templateresolver.ITemplateResolver; 22 | 23 | import javax.servlet.Servlet; 24 | import java.util.Collection; 25 | import java.util.Collections; 26 | 27 | /** 28 | * Created by bob on 17/3/9. 29 | */ 30 | @Configuration 31 | @ConditionalOnClass({Thymeleaf.class, SpringTemplateEngine.class}) 32 | @AutoConfigureAfter(WebMvcAutoConfiguration.class) 33 | public class Thymeleaf3Config { 34 | 35 | private static final String DEFAULT_PREFIX = "classpath:/templates/"; 36 | private static final String DEFAULT_SUFFIX = ".html"; 37 | 38 | @Autowired 39 | private ApplicationContext applicationContext; 40 | 41 | @Bean 42 | public SpringResourceTemplateResolver springHtmlResourceTemplateResolver() { 43 | SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); 44 | resolver.setApplicationContext(this.applicationContext); 45 | resolver.setPrefix(DEFAULT_PREFIX); 46 | resolver.setSuffix(DEFAULT_SUFFIX); 47 | resolver.setTemplateMode(TemplateMode.HTML); 48 | resolver.setCharacterEncoding("UTF-8"); 49 | resolver.setCacheable(true); 50 | resolver.setOrder(1); 51 | return resolver; 52 | } 53 | 54 | @Bean 55 | public SpringResourceTemplateResolver springTxtResourceTemplateResolver() { 56 | SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); 57 | resolver.setApplicationContext(this.applicationContext); 58 | resolver.setPrefix("classpath:/templates/text/"); 59 | resolver.setSuffix(".txt"); 60 | resolver.setTemplateMode(TemplateMode.TEXT); 61 | resolver.setCharacterEncoding("UTF-8"); 62 | resolver.setCacheable(true); 63 | resolver.setOrder(2); 64 | return resolver; 65 | } 66 | 67 | @Configuration 68 | @ConditionalOnJava(ConditionalOnJava.JavaVersion.EIGHT) 69 | @ConditionalOnClass({Java8TimeDialect.class}) 70 | protected static class ThymeleafJava8TimeDialect { 71 | 72 | @Bean 73 | @ConditionalOnMissingBean 74 | public Java8TimeDialect java8TimeDialect() { 75 | return new Java8TimeDialect(); 76 | } 77 | } 78 | 79 | @Configuration 80 | @ConditionalOnClass(name = {"nz.net.ultraq.thymeleaf.LayoutDialect"}) 81 | protected static class ThymeleafWebLayoutConfiguration { 82 | @Bean 83 | @ConditionalOnMissingBean 84 | public LayoutDialect layoutDialect() { 85 | return new LayoutDialect(); 86 | } 87 | } 88 | 89 | @Configuration 90 | @ConditionalOnMissingBean(SpringTemplateEngine.class) 91 | protected static class SpringTemplateEngineConfiguration { 92 | 93 | @Autowired 94 | private final Collection templateResolvers = Collections.emptySet(); 95 | 96 | @Autowired(required = false) 97 | private final Collection dialects = Collections.emptySet(); 98 | 99 | @Bean 100 | public SpringTemplateEngine springTemplateEngine() { 101 | SpringTemplateEngine engine = new SpringTemplateEngine(); 102 | engine.setEnableSpringELCompiler(true); 103 | for (ITemplateResolver templateResolver : this.templateResolvers) { 104 | engine.addTemplateResolver(templateResolver); 105 | } 106 | for (IDialect dialect : this.dialects) { 107 | engine.addDialect(dialect); 108 | } 109 | return engine; 110 | } 111 | } 112 | 113 | @Configuration 114 | @ConditionalOnClass({Servlet.class}) 115 | @ConditionalOnWebApplication 116 | protected static class ThymeleafViewResolverConfiguration { 117 | 118 | @Autowired 119 | private SpringTemplateEngine engine; 120 | 121 | @Bean 122 | @ConditionalOnMissingBean(name = "thymeleafViewResolver") 123 | @ConditionalOnProperty(name = "spring.thymeleaf.enabled", matchIfMissing = true) 124 | public ThymeleafViewResolver thymeleafViewResolver() { 125 | ThymeleafViewResolver resolver = new ThymeleafViewResolver(); 126 | resolver.setTemplateEngine(this.engine); 127 | resolver.setCharacterEncoding("UTF-8"); 128 | resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 5); 129 | resolver.setCache(true); 130 | return resolver; 131 | } 132 | } 133 | 134 | @Configuration 135 | @ConditionalOnWebApplication 136 | protected static class ThymeleafResourceHandlingConfig { 137 | 138 | @Bean 139 | @ConditionalOnMissingBean 140 | @ConditionalOnEnabledResourceChain 141 | public ResourceUrlEncodingFilter resourceUrlEncodingFilter() { 142 | return new ResourceUrlEncodingFilter(); 143 | } 144 | } 145 | } -------------------------------------------------------------------------------- /webapi/src/main/resources/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | Hello Spring Boot! 8 | 9 | 12 | 15 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 37 |
38 | 39 | 40 |
41 |

Test

42 |

43 | Welcome to the Spring Boot Thymeleaf Application! The time is: 31/12/2015 15:00 44 |

45 |

46 | System Properties 47 |

48 |
49 |
50 |

Spring Actuator

51 |

52 | Actuator endpoints allow you to monitor and interact with your application. 53 | Spring Boot includes a number of built-in endpoints and you can also add your own. 54 |

55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 67 | 70 | 71 | 72 | 75 | 79 | 80 | 81 | 84 | 87 | 88 | 89 | 92 | 95 | 96 | 97 | 100 | 103 | 104 | 105 | 108 | 111 | 112 | 113 | 116 | 119 | 120 | 121 | 124 | 127 | 128 | 129 | 132 | 135 | 136 | 137 | 140 | 143 | 144 | 145 | 148 | 151 | 152 | 153 |
IDDescription
65 |

loggers

66 |
68 |

Displays loggers levels

69 |
73 |

autoconfig

74 |
76 |

Displays an auto-configuration report showing all auto-configuration candidates and the 77 | reason why they “were” or “were not” applied.

78 |
82 |

beans

83 |
85 |

Displays a complete list of all the Spring Beans in your application

86 |
90 |

configprops

91 |
93 |

Displays a collated list of all @ConfigurationProperties.

94 |
98 |

dump

99 |
101 |

Performs a thread dump.

102 |
106 |

env

107 |
109 |

Exposes properties from Spring’s ConfigurableEnvironment.

110 |
114 |

health

115 |
117 |

Shows application health information (defaulting to a simple “OK” message).

118 |
122 |

info

123 |
125 |

Displays arbitrary application info.

126 |
130 |

metrics

131 |
133 |

Shows “metrics” information for the current application.

134 |
138 |

mappings

139 |
141 |

Displays a collated list of all @RequestMapping paths.

142 |
146 |

trace

147 |
149 |

Displays trace information (by default the last few HTTP requests).

150 |
154 |
155 |
156 | 157 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | org.bob.scala 6 | bootspring-scala-parent 7 | 0.0.1-SNAPSHOT 8 | 9 | webapi 10 | 11 | pom 12 | bootspring-scala-parent 13 | Scala Demo project for Spring Boot With Swagger 14 | 15 | 16 | org.springframework.boot 17 | spring-boot-starter-parent 18 | 19 | 1.5.2.RELEASE 20 | 21 | 22 | 23 | 24 | 25 | UTF-8 26 | 1.8 27 | 2.11.8 28 | 2.3.1 29 | bob.scala 30 | 0.4.5 31 | 1.3.10.Final 32 | 33 | 3.0.3.RELEASE 34 | 2.0.0 35 | 3.0.0.RELEASE 36 | 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-actuator 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-starter-web 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-starter-tomcat 50 | 51 | 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-starter-undertow 56 | 57 | 58 | org.springframework.boot 59 | spring-boot-starter-aop 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-starter-hateoas 64 | 65 | 66 | org.springframework.boot 67 | spring-boot-starter-amqp 68 | 69 | 70 | org.springframework.boot 71 | spring-boot-starter-thymeleaf 72 | 73 | 74 | org.thymeleaf.extras 75 | thymeleaf-extras-java8time 76 | 77 | 78 | org.springframework.boot 79 | spring-boot-starter-test 80 | test 81 | 82 | 83 | 84 | io.reactivex 85 | rxjava 86 | 1.2.5 87 | 88 | 89 | 90 | 91 | org.scala-lang 92 | scala-library 93 | ${scala.version} 94 | 95 | 96 | org.scala-lang 97 | scala-compiler 98 | ${scala.version} 99 | 100 | 101 | 102 | 103 | 104 | 105 | io.springfox 106 | springfox-swagger2 107 | ${springfox.version} 108 | 109 | 110 | io.springfox 111 | springfox-swagger-ui 112 | ${springfox.version} 113 | 114 | 115 | 116 | 117 | org.inferred 118 | freebuilder 119 | 1.13.2 120 | true 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | org.springframework.boot 129 | spring-boot-maven-plugin 130 | 131 | 132 | org.apache.maven.plugins 133 | maven-compiler-plugin 134 | 135 | ${java.version} 136 | ${java.version} 137 | ${project.build.sourceEncoding} 138 | 139 | 140 | 141 | 142 | 143 | net.alchim31.maven 144 | scala-maven-plugin 145 | 3.3.1 146 | 147 | 148 | scala-compile-first 149 | process-resources 150 | 151 | add-source 152 | compile 153 | 154 | 155 | 156 | scala-test-compile 157 | process-test-resources 158 | 159 | testCompile 160 | 161 | 162 | 163 | 164 | ${scala.version} 165 | incremental 166 | 167 | -Xlint:unchecked 168 | -Xlint:deprecation 169 | 170 | 171 | 172 | -nobootcp 173 | 174 | ${java.version} 175 | ${java.version} 176 | 177 | 178 | 179 | 180 | 181 | 182 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------