Spring Cloud 、OpenFeign 服务调用、Eureka注册中心搭建

Spring Cloud 、OpenFeign 服务调用、Eureka注册中心搭建

Eureka注册中心部分

maven依赖

<?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>org.example</groupId>
    <artifactId>eurekademo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
    </parent>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <!--SpringSecurity-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

    </dependencies>

    <!--打包插件-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

eureka配置文件

eureka:
  client:
    #不向自己注册服务
    register-with-eureka: false
    #不用同步节点
    fetch-registry: false
  #关闭自我保护机制
  server:
    enableSelfPreservation: false

server:
  port: 8761

spring:
  security:
    user:
      name: admin
      password: admin

启动类

@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {

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

    @EnableWebSecurity
    static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            super.configure(http);
            //关闭csrf防护
            http.csrf().disable();
        }
    }
}

如需要使用docker部署,Dockerfile

#项目所依赖的镜像
FROM java:8

ADD target/*.jar eurekademo-1.0-SNAPSHOT.jar

EXPOSE 8761

ENTRYPOINT ["java", "-jar", "eurekademo-1.0-SNAPSHOT.jar"]

ApplicationService服务提供者

maven依赖

<?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.test</groupId>
    <artifactId>springcloudredssion</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
    </parent>

    <!-- spring cloud -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        
        <!-- springmvc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--eureka-client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>

        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>

        <!-- mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>

    </dependencies>

    <!--打包插件-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置文件 application.yml

server:
  port: 8086
  
spring:
  profiles:
    active: mybatis
  application:
    name: buyapplication

eureka:
  client:
    service-url:
      defaultZone: http://admin:admin@127.0.0.1:8761/eureka/
  instance:
    hostname: 127.0.0.1
    instance-id: 127.0.0.1:8086

配置文件 application-mybatis.yml

spring:
  datasource:
    # Druid连接池
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    # 数据库的url、登录名、密码 数据库名
    url: jdbc:mysql://127.0.0.1:3306/demo?useSSL=false&characterEncoding=utf8
    username: root
    password: root

实体类

public class Goods {

    private Integer id;
    private String name;
    private Integer num;

    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 getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", num=" + num +
                '}';
    }
}

Dao

@Mapper
public interface DemoDao extends BaseMapper<Goods> {
}

Service

@Service
public class DemoServiceImpl implements DemoService {

    @Autowired
    private DemoDao demoDao;

    @Override
    public String buy(Integer id, Integer num) {
        Goods goods = demoDao.selectById(id);
        if (goods.getNum() >= num) {
            Goods updateGoods = new Goods();
            updateGoods.setId(id);
            updateGoods.setNum(goods.getNum() - num);

            Integer result = demoDao.updateById(updateGoods);
            if (result == 1) {
                return "购买成功";
            }
        }
        return "物品不够了";
    }
}

Controller

@RestController
@MapperScan("com.test.dao")
public class DemoController {

    @Autowired
    private DemoService demoService;

    @GetMapping("/buy/{id}/{num}")
    public String buy(@PathVariable Integer id, @PathVariable Integer num) {
        return demoService.buy(id,num);
    }
}

启动类

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

Dockerfile和Eureka的Dockerfile类似

如果需要搭建Service集群,把配置文件端口server.port 和 instance-id: 的端口号修后再次启动 或者再部署一份启动即可

ApplicationClient消费者部分

maven

<?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.test</groupId>
    <artifactId>cloudclient</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.7.RELEASE</version>
    </parent>

    <properties>
        <cloud-version>2.2.2.RELEASE</cloud-version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!-- spring cloud 版本-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--eureka-client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>

        <!-- openfeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>${cloud-version}</version>
        </dependency>

    </dependencies>


    <!--打包插件-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.yml

server:
  port: 8082

spring:
  application:
    name: buyclient

eureka:
  client:
    service-url:
      defaultZone: http://admin:admin@127.0.0.1:8761/eureka/
      
#如搭建集群开启负载均衡
#ribbon:
#  eureka:
#    enabled: true

FeignService

@FeignClient("buyapplication")
public interface FeignService {

    @GetMapping("/buy/{id}/{num}")
    String buy(@PathVariable Integer id, @PathVariable Integer num);

}

Service

@Service
public class BuyServiceImpl implements BuyService {

    @Autowired
    private FeignService feignService;
    
    @Override
    public String buy(Integer id, Integer num) {
        return feignService.buy(id, num);
    }
}

Controller

@RestController
public class BuyController {

    @Autowired
    private BuyService buyService;

    @GetMapping("/buy")
    public String buy() {
        return buyService.buy(1, 1);
    }
}

启动类

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

Dockerfile部分和eureka类似

sql部分

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for goods
-- ----------------------------
DROP TABLE IF EXISTS `goods`;
CREATE TABLE `goods`  (
  `id` int(11) NOT NULL,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `num` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = COMPACT;

-- ----------------------------
-- Records of goods
-- ----------------------------
INSERT INTO `goods` VALUES (1, '手机', 10);

SET FOREIGN_KEY_CHECKS = 1;
  1. 启动Eureka,输入http://localhost:8761

  2. 输入用户名密码admin admin

  3. 启动ApplicationService

  4. 启动ApplicationClientE

  5. 在注册中可以发现注册到的服务在这里插入图片描述

  6. 输入 http://localhost:8082/buy

  7. 在这里插入图片描述如果在docker容器中运行,需要修改端口号等配置信息

内容仅供参考,如有错误请指正

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值