<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.eureka.server</groupId>
<artifactId>eureka_server</artifactId>
<version>1.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.RC1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>java
1.2 啓動類
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;web
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}spring
1.3 application.ymlapache
server:
port: 8761json
eureka:
instance:
hostname: localhost
client:
#因爲該應用爲註冊中心,因此設置爲false,表明不向註冊中心註冊本身
registerWithEureka: false
#因爲註冊中心的職責就是維護服務實例,它並不須要去檢索服務,因此也設置爲false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/app
2. 服務提供方dom
包結構:maven
服務啓動類和service業務類同目錄結構
com.cloud.eureka.client.ucenter
com.cloud.eureka.client.ucenter.biz
UserInfoService.java
com.cloud.eureka.client.ucenter.domain
UserDto.java
com.cloud.eureka.client.ucenter.network
com.cloud.eureka.client.ucenter.network.request
QueryUserByIdRequest.java
com.cloud.eureka.client.ucenter.network.response
QueryUserByIdResult.java
AutoRequest.java
AutoResult.java
com.cloud.eureka.client.ucenter.service
UcenterInfoService.java
UcenterApplicationRunner.java
2 pom.xml 配置
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cloud.eureka.client</groupId>
<artifactId>ucenter</artifactId>
<packaging>war</packaging>
<version>1.0.1-SNAPSHOT</version>
<name>ucenter Maven Webapp</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR7</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>ucenter</finalName>
</build>
</project>spring-boot
2.2 application.yml
eureka:
client:
serviceUrl:
#註冊中心的地址
defaultZone: http://localhost:8761/eureka/
server:
#當前服務端口號
port: 8762
spring:
application:
#當前應用名稱
name: ucenterfetch
2.3 啓動類
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
@RestController
public class UcenterApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(UcenterApplicationRunner.class, args);
}
}
2.4 服務類和實體類 (com.cloud.eureka.client.ucenter)
import java.io.Serializable;
public class AutoResult implements Serializable {
/** */
private static final long serialVersionUID = 8058341569104586241L;
private String respCode;
private String respMsg;
public String getRespCode() {
return respCode;
}
public void setRespCode(String respCode) {
this.respCode = respCode;
}
public String getRespMsg() {
return respMsg;
}
public void setRespMsg(String respMsg) {
this.respMsg = respMsg;
}
}
import java.io.Serializable;
public class AutoRequest implements Serializable {
/*** */
private static final long serialVersionUID = 53972042882786734L;
}
import java.util.List;
import com.cloud.eureka.client.ucenter.network.AutoResult;
public class QueryUserByIdResult<T> extends AutoResult {
/** */
private static final long serialVersionUID = -5759747298893119629L;
private T model;
private List<T> modelist;
public T getModel() {
return model;
}
public void setModel(T model) {
this.model = model;
}
public List<T> getModelist() {
return modelist;
}
public void setModelist(List<T> modelist) {
this.modelist = modelist;
}
}
import com.cloud.eureka.client.ucenter.network.AutoRequest;
public class QueryUserByIdRequest extends AutoRequest {
/***/
private static final long serialVersionUID = -5959985997526831945L;
private Long userId;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.cloud.eureka.client.ucenter.biz.UserInfoService;
import com.cloud.eureka.client.ucenter.domain.UserDto;
@RestController
public class UcenterInfoService {
private final Logger logger = LoggerFactory.getLogger(UcenterInfoService.class);
@Autowired
private DiscoveryClient discoveryClient;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String index() {
ServiceInstance instance = discoveryClient.getLocalServiceInstance();
logger.info("ucenter server access index() " + this.getClass().getSimpleName() + " " + Thread.currentThread().getName());
logger.info("/hello, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());
return "Hello World";
}
@Autowired
private UserInfoService userInfoService;
@RequestMapping(value = "/queryUserInfo", method = RequestMethod.GET)
public UserDto queryUserInfo (@RequestParam("userId") Long userId) {
logger.info("ucenter server access queryUserInfo " + this.getClass().getSimpleName() + " " + Thread.currentThread().getName());
logger.info("恭喜用戶 " + userId + " 你鏈接成功");
return userInfoService.queryUserInfo();
}
@RequestMapping(value = "queryUserList", method = RequestMethod.POST)
public List<UserDto> queryUserList() {
logger.info("<=-=-=-= ucenter server access queryUserList " + this.getClass().getSimpleName()
+ " " + Thread.currentThread().getName());
List<UserDto> ulist = userInfoService.queryUserList();
return ulist;
}
@RequestMapping(value = "/queryUserById", method = RequestMethod.POST)
public QueryUserByIdResult<UserDto> queryUserUserId(QueryUserByIdRequest request) {
logger.info("<=-=-=-= ucenter server access queryUserInfo " + this.getClass().getSimpleName()
+ " " + Thread.currentThread().getName());
QueryUserByIdResult<UserDto> result = new QueryUserByIdResult<UserDto>();
UserDto dto = userInfoService.queryUserInfo();
result.setModel(dto);
result.setRespCode("000");
result.setRespMsg("查詢成功");
return result;
}
}
import org.springframework.stereotype.Service;
import com.cloud.eureka.client.ucenter.domain.UserDto;
@Service
public class UserInfoService {
public UserDto queryUserInfo() {
UserDto dto = new UserDto();
dto.setId(1l);
dto.setUserName("李世民");
dto.setAddress("陝西省咸陽市紫禁城");
System.out.println("<<=-=-=-=>>恭喜,恭喜你鏈接成功<<=-=-=-=>>");
return dto;
}
public List<UserDto> queryUserList() {
UserDto dto = new UserDto();
dto.setId(1203586l);
dto.setUserName("李世民");
dto.setAddress("陝西省咸陽市紫禁城");
UserDto dto1 = new UserDto();
dto1.setId(1022589l);
dto1.setUserName("朱江明");
dto1.setAddress("江蘇省南京市");
UserDto dto2 = new UserDto();
dto2.setId(1022575l);
dto2.setUserName("劉如海");
dto2.setAddress("湖北省省武漢市市");
List<UserDto> ulist = new ArrayList<>();
ulist.add(dto);
ulist.add(dto1);
ulist.add(dto2);
return ulist;
}
}
import java.io.Serializable;
public class UserDto implements Serializable {
private static final long serialVersionUID = 8541673794025166248L;
private Long id;
private String userName;
private String address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
3消費方
包結構 ComponentScan 與EnableEurekaClient 衝突因此啓動類與調用服務方服務要在同一級目錄不然掃描不到
com.cloud.profile
com.cloud.profile.controller
SystemController.java
com.cloud.profile.dto
UserDto.java
com.cloud.profile.third
ComsumerAppliactionRunner.java
UcenterThirdService.java
pom.xml
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cloud.profile</groupId>
<artifactId>profile</artifactId>
<packaging>war</packaging>
<version>1.0.1-SNAPSHOT</version>
<name>profile Maven Webapp</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR7</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
</dependencies>
<build>
<finalName>profile</finalName>
</build>
</project>
application.properties
server.port=8673
spring.application.name=profile
#注意此項設置爲TRUE
eureka.client.fetchRegistry=true
eureka.client.serviceUrl.defaultZone: http://localhost:8761/eureka/
eureka.client.registry-fetch-interval-seconds=30
eureka.instance.lease-expiration-duration-in-seconds=45
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
@ComponentScan(basePackages = {"com.cloud.profile.controller"})
public class ComsumerAppliactionRunner {
public static void main(String[] args) {
SpringApplication.run(ComsumerAppliactionRunner.class, args);
}
}
3.4. 第三方調用服務
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.cloud.profile.dto.UserDto;
服務名不區分大小寫
name:遠程服務名 即spring.application.name配置的名稱
@FeignClient(name= "UCENTER")
public interface UcenterThirdService {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String index();
@RequestMapping(value = "/queryUserInfo", method = RequestMethod.GET)
public UserDto queryUserInfo (@RequestParam("userId") Long userId);
@RequestMapping(value = "/queryUserList", method = RequestMethod.POST)
public List queryUserList();
@RequestMapping(value = "/queryUserById", method = RequestMethod.POST)
public QueryUserByIdResult<UserDto> queryUserById(QueryUserByIdRequest request);
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.cloud.profile.third.UcenterThirdService;
@RestController public class SystemController { private static Logger logger = LoggerFactory.getLogger(SystemController.class); @Autowired private UcenterThirdService ucenterThirdService; @RequestMapping(value = "/queryUserInfo", method = RequestMethod.GET) public String queryUserInfo (@RequestParam("userId") Long userId) { logger.info("profile response " + Thread.currentThread().getName() + " " + this.getClass().getSimpleName() + JSON.toJSONString(ucenterThirdService.queryUserInfo(userId)));; logger.info(ucenterThirdService.index()); logger.info("profile response " + Thread.currentThread().getName() + " " + this.getClass().getSimpleName() + "恭喜用戶 " + userId + " 你鏈接成功"); return "hello success"; } }