java-scala 高效混合开发

java scala 混合开发

知名应用

  • Kafka(消息系统)
  • Spark (计算引擎)
  • Play(新一代web全栈框架)
  • Akka (高可伸缩性的 Java 和 Scala 的 Actor 模型应用)

scala优点

Scala 是一种有趣的语言。它一方面吸收继承了多种语言中的优秀特性,一方面又没有抛弃 Java 这个强大的平台,它运行在 Java 虚拟机 (Java Virtual Machine) 之上,轻松实现和丰富的 Java 类库互联互通。它既支持面向对象的编程方式,又支持函数式编程。它写出的程序像动态语言一样简洁,但事实上它确是严格意义上的静态语言。Scala 就像一位武林中的集大成者,将过去几十年计算机语言发展历史中的精萃集于一身,化繁为简

与java 差别

相对于Java而言,Scala的代码更为精简(减低犯错),而且功能更为广泛(Scala其实是Scalable Language 的简称,意为可扩展的语言),许多Scala的特性和语法都是针对Java的不足和弱点来设计的。Scala的特点是有很多函数程式语言的特性(例如ML,Miranda, Scheme,Haskell),譬如惰性求值,list comprehension, type inference, anonymous function, pattern matching 等等,同时也包含 Object-Oriented 的特性(OO 能与 FP 混合使用是 Scala 的亮点)。此外,许多相似于高级编程语言的语法也渗入其中(例如 Python),不仅提高了 Scala 代码的可读性,维护、修改起来也较为省时省力。Scala 与 Java 语法上的明显差异有:不需要分号结尾类型定义开头需大写(与 Haskell 相同)函数定义需 def 开头(与 Python、Ruby 相同)return 可以省略

特点

功能多啊,语法复杂,号称是JVM上的C++

介绍

使用java和scala混合开发可以极大地提高开发效率

添加maven依赖

        <dependency>
            <groupId>org.scala-langgroupId>
            <artifactId>scala-libraryartifactId>
            <version>${scala.version}version>
        dependency>

添加插件

         <plugin>
                <groupId>org.scala-toolsgroupId>
                <artifactId>maven-scala-pluginartifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>compilegoal>
                            <goal>testCompilegoal>
                        goals>
                    execution>
                executions>
                <configuration>
                    <recompileMode>incrementalrecompileMode>
                    <scalaVersion>${scala.version}scalaVersion>
                    <launchers>
                        <launcher>
                            <id>appid>
                            <mainClass>xxxxmainClass>
                            <args>
                                <arg>-deprecationarg>
                            args>
                            <jvmArgs>
                                <jvmArg>-Xms256mjvmArg>
                                <jvmArg>-Xmx2048mjvmArg>
                            jvmArgs>
                        launcher>
                    launchers>
                configuration>
         plugin>
         <plugin>
                 <groupId>org.codehaus.mojogroupId>
                 <artifactId>build-helper-maven-pluginartifactId>
                 <version>1.8version>
                 <executions>
                     <execution>
                         <id>add-resourceid>
                         <phase>initializephase>
                         <goals>
                             <goal>add-resourcegoal>
                         goals>
                         <configuration>
                             <resources>
                                 <resource>
                                     <directory>${basedir}/src/main/resourcesdirectory>\
                                     <filtering>truefiltering>
                                     <excludes>
                                         <exclude>**/*.javaexclude>
                                     excludes>
                                 resource>
                             resources>
                         configuration>
                     execution>
                     <execution>
                         <id>add-sourceid>
                         <phase>initializephase>
                         <goals>
                             <goal>add-sourcegoal>
                         goals>
                         <configuration>
                             <sources>
                                 <source>${basedir}/src/main/javasource>
                                 <source>${basedir}/src/main/scalasource>
                             sources>
                         configuration>
                     execution>
                     <execution>
                         <id>add-test-sourceid>
                         <phase>initializephase>
                         <goals>
                             <goal>add-test-sourcegoal>
                         goals>
                         <configuration>
                             <sources>
                                 <source>${basedir}/src/test/javasource>
                             sources>
                         configuration>
                     execution>
                 executions>
         plugin> 

代码示例

  • bean

@Entity
class LazyTask {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @BeanProperty
  var id: Integer = _

  @BeanProperty
  var url: String = _
  @BeanProperty
  var name: String = _

  //用例状态: -1未执行 0失败 1成功
  @BeanProperty
  var state: Integer = _

  @BeanProperty
  var owner: String = _

  @BeanProperty
  var resultJson: String = _

  @BeanProperty
  var executeTimes: Integer = _

  @BeanProperty
  var executor: Integer = _

  @BeanProperty
  var gmtCreate: Date = _

  @BeanProperty
  var gmtModify: Date = _

}

  • dao

trait LazyTaskDao extends CrudRepository[LazyTask, Integer] {
  def findAll(): List[LazyTask]

  def save(t: LazyTask): LazyTask

  def findOne(id: Integer): LazyTask

  @Query(value = "SELECT * FROM lazy_task where url like '%?1%'", nativeQuery = true)
  def listByUrl(url: String): List[LazyTask]

  @Query(value = "SELECT * FROM lazy_task where name like '%?1%'", nativeQuery = true)
  def listByName(name: String): List[LazyTask]

}


  • Controller 示例


@RestController
class LazyTaskController @Autowired()(val lazyTaskDao: LazyTaskDao,
                                      val phantomjsExecutor: PhantomjsExecutor,
                                      val domainConfig: DomainConfig) {

  @RequestMapping(value = {
    Array("/newTask.do")
  })
  def newTask_do() = {
    new ModelAndView("ylazy/newTask")
  }

  @RequestMapping(value = {
    Array("/ylazy/newTask")
  }, method = Array(RequestMethod.POST))
  @ResponseBody
  def newTask(@ModelAttribute lazyTask: LazyTask) = {
    lazyTask.gmtCreate = new Date
    lazyTask.gmtModify = new Date
    lazyTask.executeTimes = 0
    lazyTask.state = -1
    lazyTaskDao.save(lazyTask)
  }

  @RequestMapping(value = {
    Array("/list.do")
  })
  def list_do(model: Model) = {
    model.addAttribute("lazyTaskList", lazyTaskDao.findAll())
    model.addAttribute("domainName", domainConfig.getDomainName)
    model.addAttribute("port", domainConfig.getPort)
    new ModelAndView("ylazy/list")
  }

  /**
    * 获取一条任务记录
    *
    * @param id
    * @return
    */
  @RequestMapping(value = {
    Array("/lazytask")
  }, method = Array(RequestMethod.GET))
  @ResponseBody
  def findOne(@RequestParam(value = "id") id: Integer) = lazyTaskDao.findOne(id)

  /**
    * 获取一条任务记录的返回json
    *
    * @param id
    * @return
    */
  @RequestMapping(value = {
    Array("/result/{id}")
  }, method = Array(RequestMethod.GET))
  @ResponseBody
  def findResultJson(@PathVariable(value = "id") id: Integer) = lazyTaskDao.findOne(id).resultJson

  /**
    * 执行任务
    * @param id
    * @return
    */
  @RequestMapping(value = {
    Array("/ylazy/runTask")
  }, method = Array(RequestMethod.GET))
  @ResponseBody
  def runTask(@RequestParam(value = "id") id: Integer) = {
    phantomjsExecutor.ylazyById(id)
  }

  @RequestMapping(value = {
    Array("/ylazy")
  }, method = Array(RequestMethod.GET))
  @ResponseBody
  def ylazy(@RequestParam(value = "url") url: String) = phantomjsExecutor.ylazy(url)

}

你可能感兴趣的:(java,scala,springboot)