maven+spring boot搭建简单微服务

Posted @路痴

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了maven+spring boot搭建简单微服务相关的知识,希望对你有一定的参考价值。

项目需要使用spring boot,所以自学了几天,仅提供给新手,请根据文档查看…该项目仅是测试项目,并不完善和严谨,只实现了需要使用的基本功能。写该博客一是希望能够帮助刚学习的新人,二是加深自己的印象,如果忘了也可以再看看,有些片段是从其他博客学习来的,如有问题希望能提出来,由衷的表示感谢。

主要开发环境:jdk:1.8; maven:3.3;tomcat:8等。

涉及技术:spring boot、springMVC、maven、JdbcTemplate、json、HttpClient等。

推荐博客:http://blog.csdn.net/jsyxcjw/article/details/46763639,这里有大家需要的一些理论知识,请结合参考,我就写一下简单的过程和贴代码了。

1、目录结构

  • spring boot服务中心

  • 调用者

2、数据库结构

3、服务中心的配置文件

  • beyond-cente pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.beyond.center</groupId>
    <artifactId>beyond-center</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>beyond-center-dao</module>
        <module>beyond-center-webapp</module>
    </modules>

    <repositories>
        <repository>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
            <id>public</id>
            <name>Public Repositories</name>
            <url>http://**.**.**.**:****/nexus/content/groups/public/</url>
        </repository>
    </repositories>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!-- 修改springBoot默认的java版本 -->
        <java.version>1.8</java.version>
    </properties>

    <!-- 使用spring boot的默认设置 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
    </parent>

    <!-- 不使用spring-boot-starter-parent的默认配置 -->
    <!-- <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>1.3.5.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement> -->

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
    </dependencies>
</project>
  • beyond-cente-dao pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.beyond.center</groupId>
        <artifactId>beyond-center</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>beyond-center-dao</artifactId>

    <dependencies>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>
</project>
  • beyond-center-webapp pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.beyond.center</groupId>
        <artifactId>beyond-center</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>beyond-center-webapp</artifactId>

    <dependencies>
        <dependency>
            <groupId>com.beyond.center</groupId>
            <artifactId>beyond-center-dao</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3</version>
        </dependency>
    </dependencies>

    <!-- 创建可执行的jar插件 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                        <!-- <configuration> <classifier>exec</classifier> </configuration> -->
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.beyond.Application</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>
                            jar-with-dependencies
                        </descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
  • beyond-cente-dao application.properties
spring.datasource.url=jdbc:mysql://**.**.**.**:3306/beyond?characterEncoding=UTF-8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=******
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

4、服务中心的各层访问调用类

  • model层
package com.beyond.model;

import java.io.Serializable;

public class UserInfo implements Serializable 

    private static final long serialVersionUID = 1L;

    private Integer id;
    private String name;
    private String password;
    private Integer age;

    public Integer getId() 
        return id;
    

    public void setId(Integer id) 
        this.id = id;
    

    public String getName() 
        return name;
    

    public void setName(String name) 
        this.name = name;
    

    public Integer getAge() 
        return age;
    

    public void setAge(Integer age) 
        this.age = age;
    

    public String getPassword() 
        return password;
    

    public void setPassword(String password) 
        this.password = password;
    

  • dao层
package com.beyond.mapper;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.beyond.model.UserInfo;

@Component
@SuppressWarnings( "unchecked", "rawtypes" )
public class UserInfoMapper 

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<UserInfo> selectUserInfoList() 
        // TODO Auto-generated method stub
        String sql = "select * from t_user_info ";  
        return (List<UserInfo>) jdbcTemplate.query(sql, new BeanPropertyRowMapper(UserInfo.class));  
    

    public void insertUserInfo(UserInfo userInfo) 
        // TODO Auto-generated method stub
        String sql = "insert into t_user_info (name, password, age) values(?, ?, ?)";  
        this.jdbcTemplate.update(sql, userInfo.getName(), userInfo.getPassword(), userInfo.getAge()); 
    

    public void updateUserInfo(UserInfo userInfo) 
        // TODO Auto-generated method stub
        String sql = "update t_user_info set name=?, password=?, age=? where id=?";  
        this.jdbcTemplate.update(sql, userInfo.getName(), userInfo.getPassword(), userInfo.getAge(), userInfo.getId()); 
    

    public void deleteUserInfoById(Integer id) 
        // TODO Auto-generated method stub
        String sql = "delete from t_user_info where id=?";  
        this.jdbcTemplate.update(sql, id); 
    

    public Map<String, Object> getUserInfoById(Integer id) 
        // TODO Auto-generated method stub
        String sql = "select * from t_user_info where id=?";  
        return jdbcTemplate.queryForMap(sql, new Object[]  id ); 
    


  • controller层
package com.beyond.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.beyond.mapper.UserInfoMapper;
import com.beyond.model.UserInfo;

@RestController
@RequestMapping(value = "/user")
public class UserInfoController 

    @Autowired
    private UserInfoMapper userInfoMapper;

    @RequestMapping(value = "/getUserInfoList")
    public List<UserInfo> getUserInfoList(HttpServletRequest request,
            HttpServletResponse response, ModelMap modelMap) 

         return userInfoMapper.selectUserInfoList();
    

    @RequestMapping(value = "/getUserInfoById")
    public Map<String, Object> getUserInfoById(HttpServletRequest request,
            HttpServletResponse response, ModelMap modelMap, String id) 

        if (StringUtils.isNotBlank(id)) 
            return userInfoMapper.getUserInfoById(Integer.parseInt(id));
         
        return null;
    

    @RequestMapping(value = "/editUserInfo")
    public String editUserInfo(HttpServletRequest request,
            HttpServletResponse response, ModelMap modelMap, UserInfo userInfo) 

        if (userInfo != null) 
            if (userInfo.getId() != null) 
                userInfoMapper.updateUserInfo(userInfo);
             else 
                userInfoMapper.insertUserInfo(userInfo);
            
            return "success";
         
        return "error";
    

    @RequestMapping(value = "/deleteUserInfoById")
    public String deleteUserInfoById(HttpServletRequest request,
            HttpServletResponse response, ModelMap modelMap, String id) 

        if (StringUtils.isNotBlank(id)) 
            userInfoMapper.deleteUserInfoById(Integer.parseInt(id));
            return "success";
         
        return "error";
    

  • spring boot启动访问入口
package com.beyond;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RestController;

@RestController
@ComponentScan
@EnableAutoConfiguration
public class Application 

    //启动spring boot的入口
    public static void main(String[] args) throws Exception 
        SpringApplication.run(Application.class, args);
    

5、启动spring boot

此时启动Application 的main方法,控制台显示:

默认端口号是8080,此时就可以启动spring boot了,可通过http://localhost:8080/user/getUserInfoList访问数据,结果如下:

也可以通过maven打包成jar访问,进入项目路径

打包成功后进入你写spring boot的入口类的项目中的target中执行jar

显示如下则表示执行成功,可访问

也可以将jar直接上传到Linux系统中(需配置java环境),直接执行jar

6、调用者的配置文件

  • beyond-develop pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.beyond.develop</groupId>
    <artifactId>beyond-develop</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>beyond-develop-webapp</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.6</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.6</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>3.3.3</version>
        </dependency>
    </dependencies>
</project> 
  • beyond-develop-webapp pom
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.beyond.develop</groupId>
        <artifactId>beyond-develop</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>beyond-develop-webapp</artifactId>
    <packaging>war</packaging>
    <name>beyond-develop-webapp Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>beyond-develop-webapp</finalName>
    </build>
</project>
  • spring配置文件 beyond-view.mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.1.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

    <context:component-scan base-package="com.beyond" />
    <mvc:annotation-driven />
    <context:annotation-config />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- As Spring MVC is a sub context of the root context, this needs to be configured twice -->

    <!-- i18n configuration -->
    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
        <property name="defaultLocale" value="zh_CN" />
    </bean>

    <bean id="localeChangeInterceptor"
        class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="lang" />
    </bean>

    <bean
        class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
        <property name="interceptors">
            <list>
                <ref bean="localeChangeInterceptor" />
            </list>
        </property>
    </bean>

    <!-- spring aop -->
    <aop:aspectj-autoproxy/>
</beans>
  • web.xml
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0" metadata-complete="true">
    <description>beyond</description>
    <display-name>beyond</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/spring/*.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern><

以上是关于maven+spring boot搭建简单微服务的主要内容,如果未能解决你的问题,请参考以下文章

maven+spring boot搭建简单微服务

maven 聚合工程 用spring boot 搭建 spring cloud 微服务 模块式开发项目

微服务中基于Spring Boot的maven分布式项目框架的搭建

基于Spring Boot的微服务搭建

spring boot 快速搭建 基于 Restful 风格的微服务

阿里微服务专家手写Spring Boot 实现一个简单的自动配置模块