SpringCloud+Eureka入门Demo

Posted zhangruifeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringCloud+Eureka入门Demo相关的知识,希望对你有一定的参考价值。

SpringCloud入门Demo

1、创建一个pom工程,管理版本

2、引入依赖

<?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>cn.rayfoo</groupId>
    <artifactId>SpringCloudParent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>../emp-provider</module>
        <module>../emp-consumer</module>
        <module>../Eureka-Server</module>
    </modules>
    <packaging>pom</packaging>

    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.0.4.RELEASE</version>
        <!--是否优先从本地仓库查找 为空则直接从中央仓库查找-->
        <relativePath/>
    </parent>
    <!--版本声明-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.versison>1.8</java.versison>
        <spring-cloud.version>Finchley.SR1</spring-cloud.version>
        <mapper.starter.version>2.0.3</mapper.starter.version>
        <mysql.version>5.1.32</mysql.version>
        <pageHelper.starter.version>1.2.5</pageHelper.starter.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <!--spring cloud-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--通用mapper-->
            <dependency>
                <groupId>tk.mybatis</groupId>
                <artifactId>mapper-spring-boot-starter</artifactId>
                <version>${mapper.starter.version}</version>
            </dependency>
            <!--分页插件-->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper-spring-boot-starter</artifactId>
                <version>${pageHelper.starter.version}</version>
            </dependency>
            <!--mysql驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

3、创建Eureka注册中心

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">
    <parent>
        <artifactId>SpringCloudParent</artifactId>
        <groupId>cn.rayfoo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>Eureka-Server</artifactId>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>
</project>

yml文件

server:
  port: 8761
spring:
  application:
    name: eureka-server
eureka:
  client:
    service-url:
      defaultZone : http://127.0.0.1:8761/eureka

启动器

package cn.rayfoo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

/**
 * @Author: rayfoo@qq.com
 * @Date: 2020/7/2 2:45 下午
 * @Description:
 */
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerRunner {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServerRunner.class);
    }

}

4、创建提供者

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">
    <parent>
        <artifactId>SpringCloudParent</artifactId>
        <groupId>cn.rayfoo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>emp-provider</artifactId>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>
</project>

yml

server:
  port: 8081
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
    password: root
  application:
    name: emp-provider
mybatis:
  mapper-locations: classpath*:cn.rayfoo.mapper
  type-aliases-package: cn.rayfoo.bean
  configuration:
    map-underscore-to-camel-case: true
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka

javaBean

提供者需要实现序列化、由于使用了通用mapper,需要加上Table和Id注解

package cn.rayfoo.bean;

import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @Author: rayfoo@qq.com
 * @Date: 2020/7/1 8:52 下午
 * @Description:
 */
@Table(name = "emp")
public class Employee implements Serializable {

    @Id
    private Integer empno;
    private String ename;
    private String job;
    private String mgr;
    private Date hiredate;
    private BigDecimal salary;
    private Double comm;
    private Integer deptno;

    public Integer getEmpno() {
        return empno;
    }

    public void setEmpno(Integer empno) {
        this.empno = empno;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public String getMgr() {
        return mgr;
    }

    public void setMgr(String mgr) {
        this.mgr = mgr;
    }

    public Date getHiredate() {
        return hiredate;
    }

    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }

    public BigDecimal getSalary() {
        return salary;
    }

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }

    public Double getComm() {
        return comm;
    }

    public void setComm(Double comm) {
        this.comm = comm;
    }

    public Integer getDeptno() {
        return deptno;
    }

    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "empno=" + empno +
                ", ename=‘" + ename + ‘‘‘ +
                ", job=‘" + job + ‘‘‘ +
                ", mgr=‘" + mgr + ‘‘‘ +
                ", hiredate=" + hiredate +
                ", salary=" + salary +
                ", comm=" + comm +
                ", deptno=" + deptno +
                ‘}‘;
    }

    public Employee() {
    }
}

mapper接口,注意使用的是tk包下的Mapper

package cn.rayfoo.mapper;

import cn.rayfoo.bean.Employee;
import tk.mybatis.mapper.common.Mapper;

/**
 * @Author: rayfoo@qq.com
 * @Date: 2020/7/2 2:12 下午
 * @Description:
 */
public interface EmployeeMapper extends Mapper<Employee> {
}

mapper xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.rayfoo.mapper.EmployeeMapper">

</mapper>

service

package cn.rayfoo.service;

import cn.rayfoo.bean.Employee;

/**
 * @Author: rayfoo@qq.com
 * @Date: 2020/7/2 2:15 下午
 * @Description:
 */
public interface EmployeeService {
    Employee getEmployeeById(Integer id);
}

package cn.rayfoo.service.impl;

import cn.rayfoo.bean.Employee;
import cn.rayfoo.mapper.EmployeeMapper;
import cn.rayfoo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: rayfoo@qq.com
 * @Date: 2020/7/2 2:16 下午
 * @Description:
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Employee getEmployeeById(Integer id) {
        return employeeMapper.selectByPrimaryKey(id);
    }
}

controller

package cn.rayfoo.controller;


import cn.rayfoo.bean.Employee;
import cn.rayfoo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: rayfoo@qq.com
 * @Date: 2020/7/2 2:14 下午
 * @Description:
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/{id}")
    public Employee getEmployeeById(@PathVariable Integer id){
        return employeeService.getEmployeeById(id);
    }

}

启动器

package cn.rayfoo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import tk.mybatis.spring.annotation.MapperScan;

/**
 * @Author: rayfoo@qq.com
 * @Date: 2020/7/2 2:11 下午
 * @Description:
 */
@EnableDiscoveryClient
@SpringBootApplication
@MapperScan("cn.rayfoo.mapper")
public class ProviderRunner {

    public static void main(String[] args) {
        SpringApplication.run(ProviderRunner.class);
    }

}

5、创建消费者

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">
    <parent>
        <artifactId>SpringCloudParent</artifactId>
        <groupId>cn.rayfoo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>emp-consumer</artifactId>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>
</project>

yml文件

server:
  port: 8082
spring:
  application:
    name: emp-customer
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka

JavaBean 实现序列化接口

package cn.rayfoo.bean;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @Author: rayfoo@qq.com
 * @Date: 2020/7/1 8:52 下午
 * @Description:
 */
public class Employee implements Serializable {

    private Integer empno;
    private String ename;
    private String job;
    private String mgr;
    private Date hiredate;
    private BigDecimal salary;
    private Double comm;
    private Integer deptno;

    public Integer getEmpno() {
        return empno;
    }

    public void setEmpno(Integer empno) {
        this.empno = empno;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public String getMgr() {
        return mgr;
    }

    public void setMgr(String mgr) {
        this.mgr = mgr;
    }

    public Date getHiredate() {
        return hiredate;
    }

    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }

    public BigDecimal getSalary() {
        return salary;
    }

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }

    public Double getComm() {
        return comm;
    }

    public void setComm(Double comm) {
        this.comm = comm;
    }

    public Integer getDeptno() {
        return deptno;
    }

    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "empno=" + empno +
                ", ename=‘" + ename + ‘‘‘ +
                ", job=‘" + job + ‘‘‘ +
                ", mgr=‘" + mgr + ‘‘‘ +
                ", hiredate=" + hiredate +
                ", salary=" + salary +
                ", comm=" + comm +
                ", deptno=" + deptno +
                ‘}‘;
    }

    public Employee() {
    }
}

配置类

package cn.rayfoo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: rayfoo@qq.com
 * @Date: 2020/7/2 2:29 下午
 * @Description:
 */
@Configuration
public class RestTemplateConfiguration {

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

controller

package cn.rayfoo.controller;

import cn.rayfoo.bean.Employee;
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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Author: rayfoo@qq.com
 * @Date: 2020/7/2 2:30 下午
 * @Description:
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private RestTemplate restTemplate;

    /***
     * 注入discoveryClient 注意是Spring的包
     */
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/{id}")
    public Employee getEmployeeById(@PathVariable Integer id) {
        //获取实例列表
        List<ServiceInstance> instancesList = discoveryClient.getInstances("emp-provider");
        //获取实例
        ServiceInstance instance = instancesList.get(0);
        //获取主机地址
        String hostName = instance.getHost();
        //获取端口号
        int port = instance.getPort();
        //拼接url
        String url = "http://" + hostName + ":" + port + "/employee/" + id;
        //调用接口
        Employee employee = restTemplate.getForObject(url, Employee.class);
        //返回结果
        return employee;
    }

}

启动器

package cn.rayfoo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @Author: rayfoo@qq.com
 * @Date: 2020/7/2 2:27 下午
 * @Description:
 */
@EnableDiscoveryClient
@SpringBootApplication
public class CustomerRunner {

    public static void main(String[] args) {
        SpringApplication.run(CustomerRunner.class);
    }

}

以上是关于SpringCloud+Eureka入门Demo的主要内容,如果未能解决你的问题,请参考以下文章

SpringCloud之eureka注册中心入门

创建多模块springcloud应用eureka server和client和消费端demo

SpringCloud之Eureka入门使用

SpringCloud构建微服务 | 服务注册与发现提供Demo

《SpringCloud超级入门》使用Eureka集群搭建《十三》

《SpringCloud 从入门到入土 》 第3章:服务治理:Spring Cloud Eureka