本章注意讲解spring cloud微服务两种通信方式,本章节依赖于第一、第二章节。
讲解开始前的准备如下:
一、先新建一个Maven Project模块项目,项目名称为module-oauth-server,参考第一章节步骤创建。
二、右键module-oauth-server,在该项目下创建一个Maven Module项目,项目名称为module-oauth-api。
三、再创建一个Maven Module项目,项目名称为module-oauth-resources,在pom文件依赖api项目。
项目结构图如下:
1)module-oauth-server项目pom.xml配置如下:
<?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.maven.xm</groupId>
<artifactId>module-oauth-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring.cloud.dependencies.version>Camden.SR7</spring.cloud.dependencies.version>
<io.springfox>2.7.0</io.springfox>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring.cloud.dependencies.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<modules>
<module>module-oauth-api</module>
<module>module-oauth-resources</module>
</modules>
</project>
2)module-oauth-resources项目pom.xml配置如下:
<?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>
<parent>
<groupId>com.maven.xm</groupId>
<artifactId>module-oauth-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>module-oauth-resources</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${io.springfox}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${io.springfox}</version>
</dependency>
<!-- 引用api项目 -->
<dependency>
<groupId>com.maven.xm</groupId>
<artifactId>module-oauth-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
3)module-oauth-resources项目src/main/resources下新创建一个application.properties文件,内容如下:
server.port = 8763
spring.application.name = module-oauth-server
eureka.client.serviceUrl.defaultZone = http://localhost:8761/eureka/
4)module-oauth-resources项目src/main/java下
com.maven.xm.oauth.OAuthApplication内容:
package com.maven.xm.oauth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients("com.maven.xm")
public class OAuthApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(OAuthApplication.class);
public static void main(String[] args) {
SpringApplication.run(OAuthApplication.class);
LOGGER.info("********************OAuth Server Started********************");
}
}
com.maven.xm.oauth.Swagger2内容:
package com.maven.xm.oauth;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* swagger2
* 地址: http://localhost:8763/swagger-ui.html
* @author ouyangjun
*
*/
@Configuration
@EnableSwagger2
@ComponentScan("com.maven.xm")
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.app.maven.oauth.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("更多Spring Boot相关文章请关注:http://blog.didispace.com/")
.termsOfServiceUrl("http://blog.didispace.com/")
.version("1.0")
.build();
}
}
com.maven.xm.oauth.controller.DemoController内容:
package com.maven.xm.oauth.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Api(tags = "module-oauth模块,用户Demo Controller")
@RestController
@RequestMapping(value = "/demo")
public class DemoController {
@ApiOperation(value="module模块,Test方法", notes="Test")
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello(){
return "Hello Demo ouyangjun!";
}
}
5)module-oauth-api项目pom.xml配置如下:
<?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>
<parent>
<groupId>com.maven.xm</groupId>
<artifactId>module-oauth-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>module-oauth-api</artifactId>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
</dependencies>
</project>
6)module-oauth-api项目com.maven.xm.oauth.api.IDemoApi内容如下:
package com.maven.xm.oauth.api;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @FeignClient中value的名称要跟module-oauth-resources项目中application.properties文件的name保持一致
* @author Administrator
*
*/
@FeignClient(
value = "module-oauth-server"
)
public interface IDemoApi {
@RequestMapping(value = "/demo/hello", method = RequestMethod.GET)
public String hello();
}
7)到这一步已经可以先单独运行进行访问了,先启动EurekaServerApplication,再启动OAuthApplication
启动成功之后,再浏览器地址栏中输入(该方式还不算微服务之间通信):http://localhost:8763/demo/hello
现在开始增加Fegin和ribbon通信代码:
<!-- fegin通信jar -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<!-- ribbon通信jar -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<!-- 引用其它微服务模块暴露出来的接口,不引用具体实现类 -->
<dependency>
<groupId>com.maven.xm</groupId>
<artifactId>module-oauth-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
二)在xm-web-controller项目下WebApplication.java中新增代码:
package com.maven.xm.web;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* @EnableDiscoveryClient基于spring-cloud-commons, @EnableEurekaClient基于spring-cloud-netflix。
就是如果选用的注册中心是eureka,那么就推荐@EnableEurekaClient,如果是其他的注册中心,那么推荐使用@EnableDiscoveryClient。
@EnableEurekaClient源码上有@EnableDiscoveryClient注解,可以说基本就是EnableEurekaClient有@EnableDiscoveryClient的功能
*
* @author ouyangjun
*
*/
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients("com.maven.xm")
public class WebApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(WebApplication.class);
public static void main(String[] args) {
SpringApplication.run(WebApplication.class);
LOGGER.info("********************Web Server Started********************");
}
/**
* 新增ribbon通信工具类
* @return
*/
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
三)整改一下xm-web-controller项目中DemoController.java,代码如下:
package com.maven.xm.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.maven.xm.web.service.DemoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
* @RestController注解相当于@ResponseBody + @Controller合在一起的作用
1) 如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,或者html,配置的视图解析器 InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容
2) 如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。
*
* @author ouyangjun
*
*/
@Api(tags="Demo Controller")
@RestController
@RequestMapping(value="/xm/demo")
public class DemoController {
@Autowired
private DemoService demoService;
@ApiOperation(value="Test Hello World!方法", notes="Test")
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String helloMethod(){
return demoService.helloMethod();
}
/**
* Fegin方式通信
* @return
*/
@ApiOperation(value="fegin通信Test、OAuth模块", notes="Test")
@RequestMapping(value = "/fegin/hello", method = RequestMethod.GET)
public String feginHello(){
return demoService.feginHello();
}
/**
* ribbon方式通信
* @return
*/
@ApiOperation(value="ribbon通信Test、OAuth模块", notes="Test")
@RequestMapping(value = "/ribbon/hello", method = RequestMethod.GET)
public String ribbonHello(){
return demoService.ribbonHello();
}
}
在xm-web-controller项目中新增一个DemoService.java接口,代码如下:
package com.maven.xm.web.service;
public interface DemoService {
public String helloMethod();
public String feginHello();
public String ribbonHello();
}
在xm-web-controller项目中新增一个DemoServiceImpl.java接口实现类,代码如下:
package com.maven.xm.web.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.maven.xm.oauth.api.IDemoApi;
import com.maven.xm.web.service.DemoService;
@Service
public class DemoServiceImpl implements DemoService {
@Autowired
RestTemplate restTemplate;
/**
* 引入其它微服务暴露出来的api接口
*/
@Autowired
private IDemoApi iDemoApi;
@Override
public String helloMethod() {
return "Hello Spring Cloud!";
}
@Override
public String feginHello() {
return iDemoApi.hello();
}
@Override
public String ribbonHello() {
return restTemplate.getForObject("http://module-oauth-server/demo/hello",String.class);
}
}
四)原先启动的应用不要停,如已停止原先应用,先重新启动原先两个模块,再启动WebApplication微服务
xm-web-controller服务访问,在浏览器中输入:http://localhost:8762/xm/demo/hello,界面如下:
Fegin通信方式,在浏览器中输入:http://localhost:8762/xm/demo/fegin/hello,界面展示如下:
ribbon通信方式,在浏览器中输入:http://localhost:8762/xm/demo/ribbon/hello,界面展示如下:
注意:在项目开发过程中,个人喜欢用fegin模式通信,代码方便简洁。
源码下载地址: https://gitee.com/ouyangjun_xm/springcloud/attach_files下chapter-three.rar压缩包
码云账户: oyj812438109@163.com 密码: oyj812438109@163.com
请勿恶意操作,谢谢!
本文说明:该文章属于原创,如需转载,请标明文章转载来源