Deploy maven and Nexus private services

Maven, the next free open source project belonging to the apache Software Foundation, is a cross-platform project management tool. Maven uses a concept called Project Object Model (POM) to manage projects. All project configuration information is defined in a file called POM.xml.Mainly serves Java platform-based project construction, dependency management and project information management, can automatically resolve the dependency environment of code in the project during the code deployment process, need to download the dependency environment from maven's mirror warehouse, usually slower download, enterprise will set up nexus (private service) within the company, save the dependency environment in the construction project to neXus server, improve access speed.

The POM project object model is the basic unit of work for the Maven project, an XML file that contains basic information about the project, describing how the project is built, declaring project dependencies, and so on.
When a task or target is executed, Maven looks for the POM in the current directory.Read the POM, get the required configuration information, and then execute the target.
The following configurations can be specified in POM: project dependency, plug-ins, execution goals, project build profile, project version, project development list, related mailing list information.

Maven's features:

  • JAVA projects of maven model have specification and directory planning for source code, unit test code, resources, jar packages, etc.
  • Resolve dependencies, version inconsistencies, version conflicts and other issues between projects;
  • Reasonable jar management mechanism.


The maven usage scenario (from a maintenance perspective):

  • The jar package in the original project must be manually copied and pasted into the WEB-INF/lib project. With maven, the jar package can be saved only in the warehouse. If you have a project to use, you only need to reference this file and do not need to duplicate it in the project.
  • All the jar packages needed in the original project are downloaded in advance, while maven automatically downloads the required jar packages when connected to the network.First find it in the local warehouse and download it online if you can't find it.
  • Other jar packages that a jar package depends on in the original project must be imported manually, and maven will automatically import the dependent jar packages.
  • The original project is a project, and with the help of maven, a project can be divided into multiple projects.

The project construction process includes the following steps: cleaning up the project, compiling the project, testing the project, generating test reports, packaging the project, deploying the project. These six steps are the complete construction process of a project.

Maven Warehouse
In Maven's technical terminology, a warehouse is a location where a Maven warehouse is a dependent third-party library in a project. The location of this library is called a warehouse.In Maven, any dependency, plug-in, or project-built output can be called a component.

The Maven repository helps us manage components, primarily Jar, where all JAR files (WAR, ZIP, POM, and so on) are placed.

There are three types of Maven warehouses: local, central, and remote.
Local warehouse
Maven's local repository, which is not created after Maven is installed, was created the first time the Maven command was executed.

When Maven is running, any components Maven needs are obtained directly from the local repository.If the local warehouse does not exist, it will first attempt to download components from the remote warehouse to the local warehouse, then use components from the local warehouse.

By default, whether Linux or Windows, each user has a warehouse directory with a path named.m2/respository/under his or her user directory.
Central warehouse
The Maven Central Warehouse is a warehouse provided by the Maven community that contains a large number of commonly used libraries.
Maven is built in Remote Public Warehouse
The central repository contains the vast majority of popular open source Java components, as well as source, author, SCM, information, license information, and so on.In general, simple Java project-dependent components can be downloaded here.

Core concepts of a central warehouse:

1. This warehouse is managed by the Maven community;
2. It can be used without configuration;
3. Network access is required.

Remote Warehouse (Third Party Warehouse)
Third-party warehouses are also known as internal central warehouses, also known as private services.
Private service: Generally set up by the company itself, only for internal sharing.It can be used both as an internal corporate component for collaboration and archiving, as well as as as as a public library mirror cache to reduce the frequency of external access and downloads (using private services reduces access to the central warehouse).
Learn more about it Maven Tutorial

1. Deployment of Maven

Install Maven, depending on jdk1.8
what is needed software package (Extract code: u27c) can download what I provide or download it on demand

1. Configure the jdk environment

#Detect the current jdk and uninstall it
[root@maven ~]# rpm -qa | grep jdk      
[root@maven ~]# rpm -e java-1.8.0-openjdk-headless- --nodeps
[root@maven ~]# rpm -e java-1.7.0-openjdk-headless- --nodeps
#Unzip jdk package
[root@maven ~]# tar zxf jdk-8u211-linux-x64.tar.gz -C /usr/local/
[root@maven ~]# vim /etc/profile
export  JAVA_HOME=/usr/local/jdk1.8.0_211
export  JRE_HOME=/usr/local/jdk1.8.0_211/jre
export  CLASSPATH=$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/dt.jar
export  PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH
[root@maven ~]# source /etc/profile            # Execute File Refresh Variable
[root@maven ~]# java -version           # View the current version
java version "1.8.0_211"
Java(TM) SE Runtime Environment (build 1.8.0_211-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.211-b12, mixed mode)

2. Deploy Maven

[root@maven ~]# wget
[root@maven ~]# tar zxf apache-maven-3.6.1-bin.tar.gz 
[root@maven ~]# mv apache-maven-3.6.1/ /usr/local/maven
[root@maven ~]# vim /etc/profile
export MAVEN_HOME=/usr/local/maven
[root@maven ~]# source /etc/profile        # Execute script to make configuration effective
[root@maven ~]# mvn -v           # The following version information appears when executing the command to indicate that the installation was successful
Apache Maven 3.6.1 (d66c9c0b3152b2e69ee9bac180bb8fcc8e6af555; 2019-04-05T03:00:29+08:00)
Maven home: /usr/local/maven
Java version: 1.8.0_211, vendor: Oracle Corporation, runtime: /usr/local/jdk1.8.0_211/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.10.0-514.el7.x86_64", arch: "amd64", family: "unix"

1) Build the project for testing

[root@maven ~]# mkdir /tmp/testdir
[root@maven ~]# cd /tmp/testdir/
#Execute the following command to test
[root@maven testdir]# mvn archetype:generate -DgroupId=com.zyz.maven.quickstart -DartifactIdk=testapp -DarchetypeArtifactId=maven-archetype-quickstart
#Ignore some information, enter the project name specified when the command is executed on the line below, then press Enter directly to keep the default
Define value for property 'artifactId': testapp
#When the following message appears, the installation is successful, especially on the first line of success
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  21:50 min
[INFO] Finished at: 2020-05-02T13:27:26+08:00
[INFO] ------------------------------------------------------------------------
#Create a maven project (Java type) that returns whenever there is an interaction. Cancel the interaction by adding -DinteractiveMode=false
#The above command is interpreted as follows:
# archetype:generate: Create a simple java project;
# Archtype is a prototype, a Maven plug-in, or exactly a project template, whose task is to create a project structure from the template.
#Create a simple java application using the quickstart prototype plug-in
# -DgroupId: Organization name, rewriting of company web address (reverse domain name) + project name;
# -DartifactIdk: Project name or module name;
# - DarchetypeArtifactId: Specify ArchetypeId, maven-archetype-quickstart, to create a simple Java application;
# -DinteractiveMode: Whether interactive mode is used.

Generated File Test Interpretation

[root@localhost testdir]# ls           # After successful execution of the above command, a directory named after the project name is generated in the current directory
[root@maven testdir]# cd testapp/     # Get into
[root@maven testapp]# ls              #View files generated in directory
pom.xml  src
[root@maven testapp]# cat pom.xml            # Explanation of pom file parameters
project: Root, this is right Project Add constraint information for some root elements
modelversion: Specify the current maven Version number of model
grouopId: It should be the name of the company or organization.generally speaking groupID There are three parts, each with a "."Separation, the first part is the purpose of the project, such as for business com,For noncommercial profit organizations, these are org,The second part is the company name, such as tentxun/baidu/alibaba,The third part is your project name
artifactId: Can be considered maven The name of the project you are building, for example, if you have subprojects in your project, you can use the Project Name-Naming Subprojects
packaging:  Specify the generated format ( jar/war/rar/pom/ear)
version: Version number, SNAPSHOT Meaning snapshot, indicating that the project is still under development and is an unstable version
name: Name of project, Maven Generated document uses
url: Project Home Page url,Maven Generated document uses
dependencies Tag: Specify the development build ( jar Package)
JUnit Is a Java Unit Test Framework for Language

Once the project is built successfully, the local warehouse will also be generated in the current user's host directory.

[root@maven testapp]# ls ~/.m2/repository/                   #View local warehouse catalog structure
antlr  asm  commons-codec  commons-collections  commons-io  commons-lang  jdom  net  org
[root@maven testapp]# ls ~/.m2/repository/antlr/antlr/2.7.7/
antlr-2.7.7.pom  antlr-2.7.7.pom.sha1  _remote.repositories

2) Maven Profile

Maven's profile name is: set.xml.It is stored in two places:

,/usr/local/maven/conf/settings.xml #Installed directory
,~/.m2/settings.xml #user's home directory

Installation directory configuration is also a global configuration, and user directory configuration is called user configuration.If both exist, their content will be merged and user-scoped settings.xml will take precedence.

There is no configuration file in the default user directory. You can copy settings.xml from the Maven installation directory to the user directory.

Common configuration modifications for the settings.xml file are as follows:
1. Modify the local warehouse storage path. The default value is ~/.m2/repository. The local repository in settings.xml can be modified to its desired directory.
2. If the build server cannot connect to the remote warehouse due to network failure or security issues, set the offline property to true and default to false in offline mode.
3. Modify the central warehouse server, modify the notes in the configuration file, add or modify the mirror address;
4. Set the proxy address, modify the proxy label in the configuration file, define the proxy server, and implement the proxy of maven.

Since the central warehouse server is abroad and downloads are slower in China, it is recommended that domestic users use the Aliyun warehouse address.
3) Configure and use Aliyun warehouse address

[root@maven testapp]# cd /usr/local/maven/conf/
[root@maven conf]# vim settings.xml 
     -->          # Jump to line 158 and write the following
            <name>aliyun maven</name>
  </mirrors>              # Write on this line
#Mirrors are mirror s, which provide a convenient way to switch remote warehouse addresses
#The id of the warehouse to be replaced is in <mirrorOf>central</mirrorOf>Act on the original warehouse, if * indicates replacement of all warehouses

4) Common Maven Commands

[root@maven testapp]# pwd          #Verify that the current directory is under the project you built earlier
[root@maven testapp]# mvn compile       # Compile (during compilation, you can see that the warehouse in Ali Cloud is used)
[INFO] BUILD SUCCESS         # Appearance of this line indicates successful compilation
#All commands are the same, so long as the last few lines have the above information, the execution is successful
[root@maven testapp]# ls target/             #You can see that a new directory target is generated under the directory
classes  maven-status
#target: Package the output directory, such as a packaged jar or war file;
#target/classes: Compile output directory;
[root@maven testapp]# mvn test              # Test Command
[root@maven testapp]# ls target/test-classes/                
#target/test-classes: test compilation output directory
[root@maven testapp]# mvn clean              #Cleanup command (that is, delete the directories generated by compilation and testing)
[root@maven testapp]# ls             # You can see that the target directory is gone
pom.xml  src
[root@maven testapp]# mvn package             # tar
[root@maven testapp]# ls target/                   # Will generate a jar package
classes  maven-archiver  maven-status  surefire-reports  testapp-testapp.jar  test-classes
[root@maven testapp]# mvn install              #Installation command (for uploading compressed file jar or war packages to the local repository)
# Using the maven install command directly to upload the project to the local repository,
# Then all the previous steps will be executed automatically, such as source code compilation, packaging, and so on.
[root@maven testapp]# mvn deploy      #Publish (upload package to private service, I don't have private service here, so it will fail)

5) Life cycle of mvn commands
maven is based on the central concept of building a life cycle, which means that the process of building and distributing a specific project is clearly defined as follows:

6) Build a web project, make a war package, and deploy it to Tomcat

[root@maven testdir]# mvn archetype:generate -DgroupId=cn.test.testweb -DartifactId=testweb -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
#Build a web project
#The resulting directory structure is as follows:
[root@maven testdir]# ls  testweb/
pom.xml  src
[root@maven testdir]# cat testweb/src/main/webapp/index.jsp 
<h2>Hello World!</h2>
[root@maven testdir]# cd testweb/             #Enter the project directory
[root@maven testweb]# mvn package             #Package as a war package
[root@maven testweb]# ls target/               # A target directory is generated
classes  maven-archiver  testweb  testweb.war
#Move the generated war package to Tomcat's web apps and it will automatically unzip.
#You can then access the war package generated by the Tomcat test
#Deploy Tomcat here (refer to:
[root@maven testweb]# mv target/testweb.war /usr/local/tomcat/webapps/     
[root@maven testweb]# /usr/local/tomcat/bin/ 
[root@maven testweb]# ls /usr/local/tomcat/webapps/             # You can see that you unzip after startup
docs  examples  host-manager  manager  ROOT  testweb  testweb.war

Client access to the war package moved to the root directory of the Tomcat Web page:

2. Deploy Nexus Private Service

Introduction to Nexus

Nexus is the Maven Warehouse Manager. If we use Maven, we can download the required artifact s from the Maven Central Warehouse, but this is usually not what the company does. Typically, a Maven Warehouse Server is set up locally to proxy the remote warehouse while maintaining the local warehouse to save bandwidth and time. Nexus can meet this need.In addition, it provides a powerful warehouse management function, component search function, which is based on REST, and a friendly UI is an extjs REST client, which consumes less memory and is based on a simple file system rather than a database.These advantages make it the most popular Maven warehouse manager.

Nexus is not the core concept of Maven, it is just a special Maven repository derived from it.For Maven, there are only two types of warehouses: local and remote.

The local warehouse is the local warehouse address that we configured in maven's setting.xml.Since the original local repository is empty, Maven must know at least one remote repository available to download the required components when executing the Maven command.The central warehouse is the default remote warehouse for maven.
The workflow when there is private service in the company structure is as follows:
Private service is a special kind of remote warehouse which is set up in the local area network. The purpose is to proxy the remote warehouse and deploy third-party components.With private service, when Maven needs to download a component, request it directly, and download it to the local warehouse if it exists. Otherwise, private service requests an external remote warehouse, downloads the component to the private service, and then provides it to the local warehouse for download.

Nexus functions as follows:
1. Save the bandwidth of the external network.A large number of repeated requests to external warehouses consume bandwidth. Using private service to proxy external warehouses, you can eliminate external duplicate component downloads and reduce bandwidth pressure.
2. Accelerate Maven construction.Accelerate Maven build.Connecting to requests for external warehouses is time consuming, and Maven keeps checking data from remote warehouses while performing the build.With private services, Maven only checks the data in the LAN to speed up the build.
3. Deploy third-party components.Deploy third-party components.When a component is not available from any external remote warehouse.Once private services are established, these components can be deployed to private services for internal Maven projects.
4. Improve stability and control.Improve stability and control.Maven builds are highly dependent on remote warehouses, so when the network is unstable, Maven builds become unstable or even impossible to build.Private service caches are heavily built so that Maven can function properly even if there is no external network for the time being.
5. Lower the load on the central warehouse.Lower the load on the central warehouse.Using private services can avoid many duplicate downloads to the central warehouse and reduce the pressure on the central warehouse.

1. Start deploying Nexus

[root@maven ~]# mkdir /usr/local/nexus
[root@maven ~]# tar zxf nexus-3.17.0-01-unix.tar.gz -C /usr/local/nexus/
#To start nexus, you must use the nexus user. Do not use users with high privileges, such as root, or the startup will fail
[root@maven ~]# useradd nexus
[root@maven ~]# chown -R nexus:nexus /usr/local/nexus/
[root@maven ~]# ls /usr/local/nexus/
nexus-3.17.0-01     # This is the application directory
sonatype-work         # This is the working directory for the mirror warehouse
#Run memory and working directory nexus-3.17.0-01/bin/nexus.vmoptions (modify the corresponding fields)
#Run listening address and port nexus-3.17.0-01/etc/
[root@maven ~]# ln -s /usr/local/nexus/nexus-3.17.0-01/bin/nexus /usr/local/bin/
#Create Command Soft Connection
#Switch to the nexus user and start the nexus service. If you use the root user, the start will fail because of the high privileges
[root@maven ~]# su nexus
[nexus@maven root]$ nexus start 
Starting nexus
[root@maven ~]# netstat -anput | grep 8081
tcp        0      0  *               LISTEN      4687/java     

After starting nexus, you can access the server IP+8081 port:

Follow the path prompted below to view the password:

[root@maven ~]# cat /usr/local/nexus/sonatype-work/nexus3/admin.password 

Log in. The default user name is admin and the password is what we saw above:

Change admin's password:

Create roles

Click Create:

Create User

View default warehouse type

Introduction to warehouse types:

  • Group (warehouse group type): also known as group warehouse, for the convenience of developers, their own set of warehouses
  • hosted: the publishing repository for an internal project (the repository that internal developers publish to store)
  • Proxy (proxy type): Find the warehouse of data from the remote central warehouse (you can click on the Configuration page of the corresponding warehouse to sign the value of the Remote Storage Location property, which is the path of the remote warehouse being proxied)
  • Virtual (virtual type): virtual warehouse (this is rarely needed)
  • Warehouse type under Public Repositories
  • 3rd party: A third-party released version of a component warehouse that cannot be obtained from a public warehouse, that is, a third-party dependent warehouse, and this data is usually downloaded and published by internal personnel themselves;
  • Apache Snapshots: Component repository with proxy Apache Maven repository snapshot version
  • Central: The repository used to proxy the release of version components in the maven central repository
  • entral M1 shadow: Component mirror repository for delivering a released version of M1 format in the central repository
  • Codehaus Snapshots: The repository used to proxy the snapshot version components of the Codehaus Maven repository
  • Releases: A publishing repository for the release module in an internal module to deploy a host type repository for managing internal release components; release is a release version;
  • Snapshots: A repository that publishes internal SNAPSHOT modules to deploy a host-type repository that manages internal snapshot version components; snapshots are snapshot versions, i.e. unstable versions

Open Relapse Rights for release
Repeat releases are required in development, and the corresponding permissions setting allow redeploy is required to open the release type repository.The following:

Set up agent warehouse (Aliyun maven warehouse)

URL of Ali Cloud Warehouse:

After filling out the above two items, click create repository at the bottom of the page and you will see the new Ali Cloud added.

Add the added Aliyun Proxy to the default group:

After saving, refresh the page again to see the current Nexus address:

Common usage scenarios for the above configurations are described below:

  • Release repository (nexus is built by default: maven-release ees)
  • Snapshot test center snapshot repository (nexus is built by default: maven-snapshots)
  • Central central warehouse (nexus is built by default: maven-central)
  • About Groups: Groups can be created in nexus to bring different types of warehouses together (nexus is built by default: maven-public)
  • Scenario 1: Customize the new proxy type repository, configure different call addresses in the maven configuration, or unify the custom new proxy repository into a group and call an address in the Maven configuration
  • Scenario 2: Use the proxy repository that Maven has already established and configure the Maven call address with the maven-public
  • Scenario 1 and Scenario 2 are essentially unchanged, configuring them according to the company's development habits and needs

3. Maven configures nexus private services, setting up remote warehouses for cost-effective Nexus private services

[root@maven conf]# pwd
[root@maven conf]# vim settings.xml 
      <name>nexus testconf</name>      <url></url>
#The URL above is the one you see on nexus

           ..........................#Omit some content
  #Jump to around 260 lines and write the following


  </profiles>                     #Add the above to this line, which is about 260 lines
</settings>                      #Write the <activeProfiles>field above the settings field

1. Create a maven project for testing

[root@maven conf]# rm -rf ~/.m2/                 #Delete local warehouse cache first
[root@maven testdir]# mvn archetype:generate -DgroupId=cn.zyz.zyzweb -DartifactId=zyzweb -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
#Building the project, you can see that the nexus private service address was used during the construction process.
[root@maven testdir]# ls zyzweb/
pom.xml  src
[root@maven testdir]# cd zyzweb/
[root@maven zyzweb]# mvn package                  #Package the project
[root@maven zyzweb]# ls            #After packaging, the target directory is generated
pom.xml  src  target

View the cached files in nexus (if there are no cached files, here are the solutions)

If you do not see the cached file on the page above, because you do not currently have permission to write to nexus, you can do the following:

After making these settings, delete the cached files from the local host directory again, rebuild the project, and package, you will see the cached files on nexus.
2. Configure certification and upload packaged items to nexus

[root@maven ~]# vim /usr/local/maven/conf/settings.xml 
#Search for "server" field
    -->         #Locate the line and write the following

Modify the project's pod.xml file:

[root@maven zyzweb]# pwd
[root@maven zyzweb]# ls
pom.xml  src 
[root@maven zyzweb]# vim pom.xml                 #Edit Profile  
.....................#Omit some content, the following is added manually
            <id>test-nexus</id>           #The ID here must match the ID configured for authentication in the settings file above
            <name>Nexus Snapshot</name>
                        #Above is the revised URL, which can be viewed in the web interface of nexus
            <name>Nexus releases</name>
                       #Above is the URL of the release version, which can also be seen in Repositories on the web interface
</project>                     #Add above the last line
[root@maven zyzweb]# mvn deploy           # Upload to Private Server

Confirm upload success at web interface:

Expand everything to see the following:

If an error occurs during deployment, first check that the account password of the configuration file set.xml is the same as the user password created by nexus. Then check that the id tag in the set.xml is the same as the id tag in the pom.xml file. The difference will result in a 401 (no permission) error.
3. Upload to maven-release repository

[root@maven zyzweb]# pwd
[root@maven zyzweb]# vim pom.xml 

    #Remove the "SNAPSHOT" from the above line and change it as follows:
#Save changes and exit
[root@maven zyzweb]# mvn deploy

View it in the web interface as follows:

Expand all the nodes to see the following:

4. Upload third-party maven package to nexus private service

Configure as follows (define the name and activate), then drag to the bottom of the page and click Add.

Maven Add Third Party Warehouse Address (Global Configuration)

#Edit Main Profile
[root@maven zyzweb]# vim /usr/local/maven/conf/settings.xml 
#In the previous profiles, fill in the following
          <id>3rdnexus</id>          <url></url>
  </profiles>          #Add to this Profiles tab
#Add another authentication to the previous authentication field
      <id>3rdnexus</id>      #This ID corresponds to the ID in the profile
[root@maven testdir]# ls          # Upload this jar package
[root@maven testdir]# mvn deploy:deploy-file -DgroupId=com.aliyun.oss -DartifactId=aliyun-sdk-oss -Dversion=2.6.1 -Dpackaging=jar -Dfile=/tmp/testdir/aliyun-sdk-oss-2.6.1.jar -Durl= -DrepositoryId=3rdnexus

View locally uploaded jar packages:

Tags: Maven nexus xml Java

Posted on Tue, 05 May 2020 16:27:19 -0400 by anoopd