频道栏目
首页 > 资讯 > Java > 正文

maven+spring boot搭建简单微服务

16-06-21        来源:[db:作者]  
收藏   我要投稿

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

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

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

1、目录结构

spring boot服务中心

这里写图片描述

调用者

这里写图片描述

2、数据库结构

这里写图片描述

3、服务中心的配置文件

beyond-cente pom

    4.0.0
    com.beyond.center
    beyond-center
    0.0.1-SNAPSHOT
    pom

    
        beyond-center-dao
        beyond-center-webapp
    

    
        
            
                true
            
            public
            Public Repositories
            http://**.**.**.**:****/nexus/content/groups/public/
        
    

    
        UTF-8
        
        1.8
    

    
    
        org.springframework.boot
        spring-boot-starter-parent
        1.3.5.RELEASE
    

    
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
    
beyond-cente-dao pom

    4.0.0
    
        com.beyond.center
        beyond-center
        0.0.1-SNAPSHOT
    
    beyond-center-dao

    
        
            c3p0
            c3p0
            0.9.1.2
        
        
            mysql
            mysql-connector-java
        
    
beyond-center-webapp pom

    4.0.0
    
        com.beyond.center
        beyond-center
        0.0.1-SNAPSHOT
    
    beyond-center-webapp

    
        
            com.beyond.center
            beyond-center-dao
            0.0.1-SNAPSHOT
        
        
            org.apache.commons
            commons-lang3
            3.3
        
    

    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            repackage
                        
                        
                    
                
            
            
                maven-assembly-plugin
                
                    
                        
                            com.beyond.Application
                        
                    
                    
                        
                            jar-with-dependencies
                        
                    
                
            
        
    
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 selectUserInfoList() {
        // TODO Auto-generated method stub
        String sql = "select * from t_user_info ";  
        return (List) 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 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 getUserInfoList(HttpServletRequest request,
            HttpServletResponse response, ModelMap modelMap) {

         return userInfoMapper.selectUserInfoList();
    }

    @RequestMapping(value = "/getUserInfoById")
    public Map 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


    4.0.0
    com.beyond.develop
    beyond-develop
    0.0.1-SNAPSHOT
    pom

    
        beyond-develop-webapp
    

    
        
            c3p0
            c3p0
            0.9.1.2
        
        
            org.springframework
            spring-core
            4.2.6.RELEASE
        
        
            org.springframework
            spring-expression
            4.2.6.RELEASE
        
        
            org.springframework
            spring-beans
            4.2.6.RELEASE
        
        
            org.springframework
            spring-aop
            4.2.6.RELEASE
        
        
            org.springframework
            spring-context
            4.2.6.RELEASE
        
        
            org.springframework
            spring-context-support
            4.2.6.RELEASE
        
        
            org.springframework
            spring-jms
            4.2.6.RELEASE
        
        
            org.springframework
            spring-tx
            4.2.6.RELEASE
        
        
            org.springframework
            spring-web
            4.2.6.RELEASE
        
        
            org.springframework
            spring-webmvc
            4.2.6.RELEASE
        
        
            org.aspectj
            aspectjweaver
            1.8.6
        
        
            org.aspectj
            aspectjrt
            1.8.6
        
        
            commons-logging
            commons-logging
            1.1.1
        
        
            net.sf.json-lib
            json-lib
            2.4
            jdk15
        
        
            org.apache.maven
            maven-plugin-api
            3.3.3
        
    
 
beyond-develop-webapp pom


    4.0.0
    
        com.beyond.develop
        beyond-develop
        0.0.1-SNAPSHOT
    
    beyond-develop-webapp
    war
    beyond-develop-webapp Maven Webapp
    http://maven.apache.org

    
        
            jstl
            jstl
            1.2
        
        
            javax.servlet
            javax.servlet-api
            3.1.0
        
        
            javax.servlet.jsp
            jsp-api
            2.1
            provided
        
        
            taglibs
            standard
            1.1.2
        
        
            org.apache.httpcomponents
            httpclient
            4.5.1
        
        
            org.apache.commons
            commons-lang3
            3.3
        
    

    
        beyond-develop-webapp
    

spring配置文件 beyond-view.mvc.xml



    
    
    

    
        
        
    

    

    
    
        
    

    
        
    

    
        
            
                
            
        
    

    
    
web.xml



    beyond
    beyond

    
        contextConfigLocation
        classpath*:/spring/*.xml
    

    
        org.springframework.web.context.ContextLoaderListener
    

    
        org.springframework.web.context.request.RequestContextListener
    

    
        encodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
    

    
        encodingFilter
        /*
    

    
        DispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath*:/spring/beyond-*.mvc.xml
        
        1
    

    
        DispatcherServlet
        *.shtml
    

     
        30 
     
      
          
            http://java.sun.com/jstl/fmt  
            /WEB-INF/tlds/fmt.tld  
          
          
            http://java.sun.com/jstl/fmt-rt  
            /WEB-INF/tlds/fmt-rt.tld  
          
    


7、调用者的各访问类

controller层
package com.beyond.controller;

import java.util.HashMap;
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.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.beyond.service.UserInfoService;

@Controller
@RequestMapping(value = "user")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping(value = "/getUserInfoList.shtml")
    public String getUserInfoList(HttpServletRequest request,
            HttpServletResponse response, ModelMap modelMap) {

        List<>> userInfos = userInfoService.selectUserInfoList();
        request.setAttribute("userInfos", userInfos);
        return "user/getUserInfoList";
    }

    @RequestMapping(value = "/goToEditUserInfo.shtml")
    public String goToEditUserInfo(HttpServletRequest request,
            HttpServletResponse response, ModelMap modelMap, String id) {

        if (StringUtils.isNotBlank(id)) {
            Map userInfo = userInfoService.getUserInfoById(id);
            request.setAttribute("userInfo", userInfo);
        }
        return "user/editUserInfo";
    }

    @RequestMapping(value = "/editUserInfo.shtml")
    @ResponseBody
    public String editUserInfo(HttpServletRequest request,
            HttpServletResponse response, ModelMap modelMap) {

        //将form表单参数封装为map
        Map parameters = new HashMap();
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            parameters.put("id", id);
        }
        String name = request.getParameter("name");
        if (StringUtils.isNotBlank(name)) {
            parameters.put("name", name);
        }
        String password = request.getParameter("password");
        if (StringUtils.isNotBlank(password)) {
            parameters.put("password", password);
        }
        String age = request.getParameter("age");
        if (StringUtils.isNotBlank(age)) {
            parameters.put("age", age);
        }
        return userInfoService.editUserInfo(parameters);
    }


    @RequestMapping(value = "/deleteUserInfo.shtml")
    @ResponseBody
    public String deleteUserInfo(HttpServletRequest request,
            HttpServletResponse response, ModelMap modelMap) {

        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            return userInfoService.deleteUserInfo(id);
        }
        return "error";
    }

}
service层
package com.beyond.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Service;

import com.beyond.service.common.HttpClientService;
import com.beyond.util.JsonUtil;

@Service
public class UserInfoService extends HttpClientService {

    public List<>> selectUserInfoList(){
        httpclient = HttpClients.createDefault(); 
        List<>> jsonObjects = null;
        String json = getHttpClient(IP + "user/getUserInfoList");
        if (StringUtils.isNotBlank(json)) {
            if (json.equals("error")) {
                return null;
            } else {
                jsonObjects = JsonUtil.getObjectList(json);
            }
        }
        return jsonObjects;
    }

    public Map getUserInfoById(String id) {
        httpclient = HttpClients.createDefault(); 
        Map jsonObject = null;
        //将id属性和值存到http请求参数队列 
        List formparams = new ArrayList<>();
        formparams.add(new BasicNameValuePair("id", id)); 
        String json = postHttpClient(IP + "user/getUserInfoById", formparams);
        if (StringUtils.isNotBlank(json)) {
            if (json.equals("error")) {
                return null;
            } else {
                Map map = new HashMap<>();
                map.put("id", Integer.class);
                jsonObject = (Map)JsonUtil.getObject(json, map);
            }
        }
        return jsonObject;
    }

    public String editUserInfo(Map parameters) {
        httpclient = HttpClients.createDefault(); 
        //将form表单数据存到http请求参数队列 
        List formparams = new ArrayList<>();
        Iterator iterator = parameters.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry entry = (Entry)iterator.next();
            formparams.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString())); 
        }
        return postHttpClient(IP + "user/editUserInfo", formparams);
    }

    public String deleteUserInfo(String id) {
        httpclient = HttpClients.createDefault(); 
        //将id属性和值存到http请求参数队列 
        List formparams = new ArrayList<>();
        formparams.add(new BasicNameValuePair("id", id)); 
        return postHttpClient(IP + "user/deleteUserInfoById", formparams);
    }

}
HttpClient访问处理类
package com.beyond.service.common;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

@Service
public class HttpClientService {

    //启动spring boot服务的IP地址
    protected static final String IP = "http://**.**.**.**:8080/";
    protected CloseableHttpClient httpclient;

    /**
     * get请求HttpClient返回实体或error
     * @param address 请求地址
     * @return
     */
    protected String getHttpClient(String address) {
        String result = "";
        try {
            HttpGet httpGet = new HttpGet(address);  
            CloseableHttpResponse response = httpclient.execute(httpGet);

            try {
                HttpEntity entity = response.getEntity();  
                if (entity != null) {  
                    if (response.getStatusLine().getStatusCode() == 200) {
                        //获取响应结果json
                        result = EntityUtils.toString(entity);
                        EntityUtils.consume(entity);
                    } else {
                        result = "error";
                    }
                }
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  finally {
                response.close();  
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  finally {  
            if (httpclient != null) {  
                try {  
                    httpclient.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
        return result;
    }

    /**
     * post请求HttpClient返回执行结果
     * @param address 请求地址
     * @param formparams 请求参数
     * @return
     */
    protected String postHttpClient(String address, List formparams) {
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(address);  
            // 创建请求参数队列 
            UrlEncodedFormEntity uefEntity;
            if (formparams != null && formparams.size() > 0) {
                uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
                httpPost.setEntity(uefEntity);  
            }
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                HttpEntity entity = response.getEntity();  
                if (entity != null) {  
                    if (response.getStatusLine().getStatusCode() == 200) {
                        result = EntityUtils.toString(entity);
                        EntityUtils.consume(entity);
                    } else {
                        result = "error";
                    }
                }
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  finally {
                response.close();  
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  finally {  
            if (httpclient != null) {  
                try {  
                    httpclient.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
        return result;
    }
}
访问spring boot返回的结果处理类
package com.beyond.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class JsonUtil {

    /**
     * 根据json和属性值返回对应Map类型实体,key:属性名;value:属性值
     * @param json
     * @param map 实体类对应属性值
     * @return
     */
    public static Map getObject(String json, Map map) {
        Map jsonObject = null;
        try {
            jsonObject = JSONObject.fromObject(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 根据json返回List类型实体集合,key:属性名;value:属性值
     * @param json
     * @param map
     * @return
     */
    public static List<>> getObjectList(String json) {
        JSONArray array = JSONArray.fromObject(json);
        List<>> list = new ArrayList<>>();
        for (Iterator iter = array.iterator(); iter.hasNext();) {
            Map jsonObject = (Map) iter.next();
            list.add(jsonObject);
        }
        return list;
    }
}

页面省略…

8、启动调用者

此时启动调用者,就可以直接访问spring boot的服务中心
这里写图片描述

相关TAG标签
上一篇:Spring Cache集成redis
下一篇:【C++】泛型编程基础:模板通识
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站