java-scala 高效混合开发

本文探讨了Java和Scala的混合开发,介绍了如何在知名应用如Kafka、Spark和Play中使用Scala,并阐述了Scala相比Java的优势,如代码精简、功能广泛,以及其在面向对象和函数式编程中的融合特性。同时,文章提供了添加Maven依赖和使用插件的指导,并给出了代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>${scala.version}</version>
        </dependency>

添加插件

         <plugin>
                <groupId>org.scala-tools</groupId>
                <artifactId>maven-scala-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <recompileMode>incremental</recompileMode>
                    <scalaVersion>${scala.version}</scalaVersion>
                    <launchers>
                        <launcher>
                            <id>app</id>
                            <mainClass>xxxx</mainClass>
                            <args>
                                <arg>-deprecation</arg>
                            </args>
                            <jvmArgs>
                                <jvmArg>-Xms256m</jvmArg>
                                <jvmArg>-Xmx2048m</jvmArg>
                            </jvmArgs>
                        </launcher>
                    </launchers>
                </configuration>
         </plugin>
         <plugin>
                 <groupId>org.codehaus.mojo</groupId>
                 <artifactId>build-helper-maven-plugin</artifactId>
                 <version>1.8</version>
                 <executions>
                     <execution>
                         <id>add-resource</id>
                         <phase>initialize</phase>
                         <goals>
                             <goal>add-resource</goal>
                         </goals>
                         <configuration>
                             <resources>
                                 <resource>
                                     <directory>${basedir}/src/main/resources</directory>\
                                     <filtering>true</filtering>
                                     <excludes>
                                         <exclude>**/*.java</exclude>
                                     </excludes>
                                 </resource>
                             </resources>
                         </configuration>
                     </execution>
                     <execution>
                         <id>add-source</id>
                         <phase>initialize</phase>
                         <goals>
                             <goal>add-source</goal>
                         </goals>
                         <configuration>
                             <sources>
                                 <source>${basedir}/src/main/java</source>
                                 <source>${basedir}/src/main/scala</source>
                             </sources>
                         </configuration>
                     </execution>
                     <execution>
                         <id>add-test-source</id>
                         <phase>initialize</phase>
                         <goals>
                             <goal>add-test-source</goal>
                         </goals>
                         <configuration>
                             <sources>
                                 <source>${basedir}/src/test/java</source>
                             </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)

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值