阅读 137

k8s部署SpringCloud G版 provider

1、编写微服务msc-provider8081并部署到K8S

1.1 创建微服务工程msc-provider8081

idea创建一个 Spring Initializr 工程,并命名为 msc-provider-8081。导入 Lombok、Web、JPA 及 MySQL 驱动依赖。


pom.xml添加依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.12.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.jd</groupId>
    <artifactId>msc-provider8081</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>msc-provider8081</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR5</spring-cloud.version>
    </properties>
    <dependencies>
        <!--actuator依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!--eureka客户端依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

        <!--修改MySQL驱动版本-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
复制代码

定义实体类

package com.jd.bean;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Data
@Entity //使用自动建表
@JsonIgnoreProperties({"hibernateLazyInitializer""handler""fieldHandler"}) //忽略hibernate延迟加载等特性
public class Depart {
    @Id //表示当前属性为自动建的表的主键
    @GeneratedValue(strategy= GenerationType.IDENTITY)//主键自动递增
    private Integer id;
    private String name;
}
复制代码

定义 Repository 接口

package com.jd.repository;


import com.jd.bean.Depart;
import org.springframework.data.jpa.repository.JpaRepository;

//第一个泛型是当前Repository所操作对象的类型
//第二个泛型是当前Repository所操作对象的id类型
public interface DepartRepository extends JpaRepository<Depart,Integer{


}
复制代码

定义 Service 接口

package com.jd.service;


import com.jd.bean.Depart;
import java.util.List;

public interface DepartService {

    boolean saveDepart(Depart depart);
    boolean removeDepartById(Integer id);
    boolean modifyDepart(Depart depart);
    Depart getDepartById(int id);
    List<Depart> listAllDeparts();
}
复制代码

定义 Service 实现类

package com.jd.service;

import com.jd.bean.Depart;
import com.jd.repository.DepartRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DepartServiceImpl implements DepartService {

    @Autowired
    private DepartRepository repository;

    @Override
    public boolean saveDepart(Depart depart) {
        Depart obj = repository.save(depart);
        return obj != nulltrue : false;
    }

    @Override
    public boolean removeDepartById(Integer id) {
        if(repository.existsById(id)){
            repository.deleteById(id);
            return true;
        }
        return false;
    }

    @Override
    public boolean modifyDepart(Depart depart) {
        Depart obj = repository.save(depart);
        return obj != nulltrue : false;
    }

    @Override
    public Depart getDepartById(int id) {
        if(repository.existsById(id)){
            return repository.getOne(id);
        }
        Depart depart = new Depart();
        depart.setName("no this depart");
        return depart;
    }

    @Override
    public List<Depart> listAllDeparts() {

        return repository.findAll();
    }
}
复制代码

定义处理器

package com.jd.controller;

import com.jd.bean.Depart;
import com.jd.service.DepartService;
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.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/provider/depart")
public class DepartController {

    @Autowired
    private DepartService departService;

    @PostMapping("/save")
    public boolean saveHandler(@RequestBody Depart depart){
        return departService.saveDepart(depart);
    }

    @DeleteMapping("/del/{id}")
    public boolean delHandler(@PathVariable("id") Integer id){
        return departService.removeDepartById(id);
    }

    @PutMapping("/update")
    public boolean updateHandler(@RequestBody Depart depart){
        return departService.modifyDepart(depart);
    }

    @GetMapping("/get/{id}")
    public Depart getHandler(@PathVariable("id") Integer id){
        return departService.getDepartById(id);
    }

    @GetMapping("/list")
    public List<Depart> listHandler(){
        return departService.listAllDeparts();
    }
}
复制代码

配置文件 application.yml

server:
  port: 8081
spring:
  #指定微服务对外暴露的名称
  application:
    name: msc-provider
  #配置jpa
  jpa:
    generate-ddl: true #指定是否在spring启动时创建表 默认false
    show-sqltrue #指定在控制台是否显示sql语句 默认false
    hibernate:
      ddl-autonone #指定应用重启后不重新更新表内容


  #配置
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://192.168.56.72:3306/kkb?useUnicode=true&amp;characterEncoding=utf8
    username: root
    password: root


eureka:
  instance:
    prefer-ip-address: true #注册服务的时候使用服务的ip地址
  client:
    service-url:
#cluster-ip 的地址
      defaultZone: http://10.68.96.71:8761/eureka 
复制代码

将工程打包

1.2 部署微服务服务提供者msc-provider8081到K8S集群

1.2.1 将工程的jar包上传到CentOS机器上

[root@master01 ~]# mkdir -p /root/app/demo/provider

1.2.2 在目录/root/app/demo/provider下创建Dockerfile文件

[root@master01 provider]# cat Dockerfile

# 基于哪个镜像
FROM java:8
# 将本地文件夹挂载到当前容器
VOLUME /root/app/demo/provider
# 复制文件到容器
ADD  provider.jar /provider.jar
# 声明需要暴露的端口
EXPOSE 8081
# 配置容器启动后执行的命令
ENTRYPOINT ["java","-jar","/provider.jar"]
复制代码

1.2.3 用Dockerfile构建微服务镜像

在目录/root/app/demo/provider下执行 docker build构建镜像
[root@master01 provider]# docker build -t microservice-provider:v1 .
[root@master01 provider]# docker tag microservice-provider:v1 registry.cn-beijing.aliyuncs.com/registry_tomato/microservice-provider:v1

1.2.4 镜像上传到阿里云 Hub

备注:docker 需要先登录 docker login

[root@master01 provider]# docker push registry.cn-beijing.aliyuncs.com/registry_tomato/microservice-provider:v1

1.2.5 创建集群部署文件 provider.yaml

[root@master01 provider]# cat provider.yml

#deploy
apiVersion: apps/v1
kind: Deployment
metadata:
  name: provider
spec:
  selector:
    matchLabels:
      app: provider
  replicas: 1
  template:
    metadata:
      labels:
        app: provider
    spec:
      containers:
      - name: provider
        image: registry.cn-beijing.aliyuncs.com/registry_tomato/microservice-provider:v1
        ports:
        - containerPort: 8081
---
#service
apiVersion: v1
kind: Service
metadata:
  name: provider-service
spec:
  ports:
  - port: 8081
    nodePort: 38081
    protocol: TCP
  type: NodePort
  selector:
    app: provider
复制代码

1.2.6 启动服务提供者

[root@master01 provider]# kubectl apply -f provider.yml

1.2.7 查看pod副本和service

[root@master01 provider]# kubectl get pods -o wide

[root@master01 provider]# kubectl get svc -o wide

1.2.8 测试和验证

测试添加

根据id查询

修改数据

查询所有

根据id删除