码迷,mamicode.com
首页 > 编程语言 > 详细

maven+spring boot搭建简单微服务

时间:2016-06-21 06:40:22      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:

项目需要使用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>
    </filter-mapping>

    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:/spring/beyond-*.mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>*.shtml</url-pattern>
    </servlet-mapping>

    <session-config> 
        <session-timeout>30</session-timeout> 
    </session-config> 
    <jsp-config>  
        <taglib>  
            <taglib-uri>http://java.sun.com/jstl/fmt</taglib-uri>  
            <taglib-location>/WEB-INF/tlds/fmt.tld</taglib-location>  
        </taglib>  
        <taglib>  
            <taglib-uri>http://java.sun.com/jstl/fmt-rt</taglib-uri>  
            <taglib-location>/WEB-INF/tlds/fmt-rt.tld</taglib-location>  
        </taglib>  
    </jsp-config>

</web-app>

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<Map<String, Object>> 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<String, Object> 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<String, String> parameters = new HashMap<String, String>();
        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<Map<String, Object>> selectUserInfoList(){
        httpclient = HttpClients.createDefault(); 
        List<Map<String, Object>> 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<String, Object> getUserInfoById(String id) {
        httpclient = HttpClients.createDefault(); 
        Map<String, Object> jsonObject = null;
        //将id属性和值存到http请求参数队列 
        List<NameValuePair> 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<String, Object> map = new HashMap<>();
                map.put("id", Integer.class);
                jsonObject = (Map<String, Object>)JsonUtil.getObject(json, map);
            }
        }
        return jsonObject;
    }

    public String editUserInfo(Map<String, String> parameters) {
        httpclient = HttpClients.createDefault(); 
        //将form表单数据存到http请求参数队列 
        List<NameValuePair> 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<NameValuePair> 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<NameValuePair> 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<String, Object> getObject(String json, Map map) {
        Map<String, Object> jsonObject = null;
        try {
            jsonObject = JSONObject.fromObject(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

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

页面省略…

8、启动调用者

此时启动调用者,就可以直接访问spring boot的服务中心
技术分享

maven+spring boot搭建简单微服务

标签:

原文地址:http://blog.csdn.net/zjm9109/article/details/51722034

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!