springcloud eureka 服务注册和发现

<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>

1.2 启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }    
}

1.3 application.yml

server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  client:
    #由于该应用为注册中心,所以设置为false,代表不向注册中心注册自己
    registerWithEureka: false
    #由于注册中心的职责就是维护服务实例,它并不需要去检索服务,所以也设置为false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

2. 服务提供方
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>

2.2 application.yml
eureka:
  client:
    serviceUrl:
      #注册中心的地址
      defaultZone: http://localhost:8761/eureka/
server:
  #当前服务端口号
  port: 8762
spring:
  application:
    #当前应用名称
    name: ucenter

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消费方
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
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配置的名称

@Component
@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";
     }
}

猜你喜欢

转载自my.oschina.net/u/2510361/blog/1821171