Example of building lightweight services using Spark in java

Source: Internet
Author: User

Let's look at the next simplest example.

1. Add in pom. xml

<Dependency>
<GroupId> com. sparkjava </groupId>
<ArtifactId> spark-core </artifactId>
<Version> 2.0.0 </version>
</Dependency>
2. Create a new Class

Import static spark. Spark .*;

Public class HelloWorld {
Public static void main (String [] args ){
Get ("/hello", (req, res)-> "Hello World ");
    }
}
Run HelloWorld directly to access http: // localhost: 4567/hello. The page displays Hello World.

Java can be written so concisely...

II. spark packaging and running

How to enable this lightweight application service? The simplest startup method is

Java-jar ***. jar
In this way, as long as JDK is installed on the server, no other Maven or Tomcat installation is required.

In fact, packaging is very simple. Applications built by Maven can directly use Plugins.

<Plugin>
<GroupId> org. apache. maven. plugins </groupId>
<ArtifactId> maven-compiler-plugin </artifactId>
<Configuration>
<Sources> 1.8 </source>
<Target> 1.8 </target>
<Encoding> UTF-8 </encoding>
</Configuration>
</Plugin>
<Plugin>
<GroupId> org. apache. maven. plugins </groupId>
<ArtifactId> maven-jar-plugin </artifactId>
<Configuration>
<Archive>
<Manifest>
<AddClasspath> true </addClasspath>
<ClasspathPrefix> lib </classpathPrefix>
<MainClass> net. coding. gravatar. Application </mainClass>
</Manifest>
</Archive>
</Configuration>
</Plugin>
<Plugin>
<GroupId> org. apache. maven. plugins </groupId>
<ArtifactId> maven-dependency-plugin </artifactId>
<Executions>
<Execution>
<Id> copy </id>
<Phase> package </phase>
<Goals>
<Goal> copy-dependencies </goal>
</Goals>
<Configuration>
<OutputDirectory>
$ {Project. build. directory}/lib
</OutputDirectory>
</Configuration>
</Execution>
</Executions>
</Plugin>
III. Use cases of Spark

For small services, Spark can accelerate development and have low requirements for building the server environment, as long as you have a JDK environment (note: JDK 8 is required for the JDK Version)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.