天天看点

springcloud(一)| eureka:服务的注册与发现一.eureka-server二.eureka-client

你要足够努力,才能够游刃有余

学了好一段时间的springcloud了,写个系列记录一下,方便快速回忆

快速开始springcloud-eureka

  • 一.eureka-server
    • 1.新建maven模块
    • 2.写pom
    • 3.写yml
    • 4.写主启动类
    • 5.拓展-增加主机映射
  • 二.eureka-client
    • 1.新建maven模块
    • 2.写pom
    • 3.写yml
    • 4.写主启动类
    • 5.业务逻辑代码

一.eureka-server

eureka分为服务端和客户端:

  • 服务端:注册中心
    • 构建高可用的注册中心集群后,每个注册中心也是体系中的客户端,只是注册中心除了作为客户端之外,还为其他客户端提供了服务注册的特殊功能
  • 客户端:提供接口的微服务应用

1.新建maven模块

选择新建一个maven模块,用作于服务端的注册中心。

2.写pom

<dependencies>
        <!--eureka-server-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <!--springboot-web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--启动图形监控-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>
           

3.写yml

主机地址映射(eureka7001.com)的增加—>映射

server:
  port: 7001
spring:
  application:
    name: cloud-eureka-server    
eureka:
  instance:
    hostname: eureka7001.com     #实例名称
  client:
    register-with-eureka: false  #不必注册自己
    fetchRegistry: false         #不要检索服务
    service-url:
      #集群模式
      defaultZone: http://eureka7002.com:7002/eureka/
      #单机模式
      #defaultZone: http://eureka7001.com:7001/eureka/
    server:
      enable-self-preservation: true    #自我保护机制,true为打开,默认打开
      #lease-renewal-interval-in-seconds:1         #Eureka客户端向服务端发送心跳的时间间隔,单位为秒(默认是30秒)
      #lease-expiration-duration-in-seconds: 2      #Eureka服务端在收到最后一次心跳后等待时间上限 ,单位为秒(默认是90秒),超时剔除服务

           

4.写主启动类

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

5.拓展-增加主机映射

为了方便在eureka的识别和管理,可以增加主机地址映射。

  1. 找到

    C:\Windows\System32\drivers\etc

    路径下的hosts文件
  2. 在最后面编辑增加如下字符:
127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com
           

二.eureka-client

有了服务端之后,就注册客户端在注册中心上,消费者端就可以在eureka进行服务间的调用

1.新建maven模块

新建一个maven用作client

为了方便项目的快速建成,客户端和提供一起详细写

2.写pom

<dependencies>
        <!--springboot 初始化和图形监控管理-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--Spring cloud alibaba 2.1.0.RELEASE-->
        <!--数据库连接相关配置-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--Eureka-Client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--注解注入功能-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--test插件功能-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
           

3.写yml

server:
  port: 8001
spring:
  application:
    name: cloud-book-service
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db2019?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    username: root
    password: 123456
mybatis:
  mapperLocations: classpath:mapper/*.xml
  type-aliases-package: com.lyj.springcloud.entities
eureka:
  client:
    register-with-eureka: true
    fetchRegistry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
  instance:
    instance-id: book-one
    prefer-ip-address: true
           

4.写主启动类

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

5.业务逻辑代码

这里简单写一下增删改查操作:

1.dao层

@Mapper //告诉sprigng框架此接口的实现类由Mybatis负责创建,并将其实现类对象存储到spring容器并管理。
public interface BookDao {
    //@Param可以简化在xml文件中参数的parameterType配置
    //查看
    public List<BookInf> getAllBooks();
    //增加
    public int addBook(BookInf book);
    //删除
    public int deleteBook(@Param("bookid") int id);
    //修改
    public int update(BookInf book);
}
           

2.Mapper

  • 对dao层接口进行映射
  • 也就是接口的实现

在resources新建mapper文件,新建 .xml文件

<mapper namespace="com.lyj.springcloud.dao.BookDao">	<!--对应的dao层接口路径-->
	<!---->
    <select id="getAllBooks" resultMap="BooksInfMap">	<!--resultMap是数据返回类型,这里进行自定义-->
        select * from bookinf
    </select>
    <resultMap id="BooksInfMap" type="com.lyj.springcloud.entities.BookInf">	<!--自定义的数据返回类型-->
        <id column="bookid" property="bookid" jdbcType="BIGINT"></id>
        <id column="bookname" property="bookname" jdbcType="VARCHAR"></id>
        <id column="bookauthor" property="bookauthor" jdbcType="VARCHAR"></id>
        <id column="bookcontent" property="bookcontent" jdbcType="VARCHAR"></id>
    </resultMap>

	<!--parameterType主要用于指定传入对象类型,如果不指定,会直接获取,接口参数,指定则是获取对象类的属性-->
    <insert id="addBook" parameterType="BookInf" useGeneratedKeys="true" keyProperty="bookid">
        insert into bookinf(bookid,bookname,bookauthor,bookcontent) values(#{bookid},#{bookname},#{bookauthor},#{bookcontent});
    </insert>

    <update id="update" parameterType="BookInf" useGeneratedKeys="true" keyProperty="bookid">
        UPDATE bookinf SET bookname=#{bookname},bookauthor=#{bookauthor},bookcontent=#{bookcontent} WHERE bookid=#{bookid}
    </update>

    <delete id="deleteBook" parameterType="INTEGER">
        delete from bookinf where bookid=#{bookid}
    </delete>
</mapper>
           

3.service

新建service接口,写以下代码:

public interface BookService {
    //查看
    public List<BookInf> getAllBooks();
    //增加
    public int addBook(BookInf book);
    //删除
    public int deleteBook(@Param("bookid")int id);
    //修改
    public int update(BookInf book);
}
           

新建serviceImpl实现类:

@Service	//service标注业务层组件,交给spring容器管理,需要为其自动创建对象
public class BookServiceImpl implements BookService {

    @Resource
    private BookDao bookDao;

    @Override
    public List<BookInf> getAllBooks() {
        return bookDao.getAllBooks();
    }

    @Override
    public int addBook(BookInf book) {
        return bookDao.addBook(book);
    }

    @Override
    public int deleteBook(@Param("bookid")int id) {
        return bookDao.deleteBook(id);
    }

    @Override
    public int update(BookInf book) {
        return bookDao.update(book);
    }
}
           

3.controller

创建controller文件夹,新建controller.class

@RestController
@Slf4j
public class BookController {
    @Resource
    private BookService bookService;
    
    @GetMapping(value = "/book/getAllBooks")
    public CommonResult getAllBooks(){
        List<BookInf> bookList = bookService.getAllBooks();
        CommonResult commonResult ;
        if (bookList.size()==0){
            commonResult = new CommonResult(404, "default", "null");
        }else {
            commonResult =  new CommonResult(200,"success",bookList);
        }
        return commonResult;
    }

    @PostMapping(value = "/book/addBook")
    public CommonResult addBook(@RequestBody BookInf book){
        System.out.println("8001端口----->"+book);
        int number = bookService.addBook(book);
        CommonResult addBookCommonResult;
        if (number == 0){
            addBookCommonResult = new CommonResult(404,"default","null");
        }else {
            addBookCommonResult = new CommonResult(200,"success","success");
        }
        return addBookCommonResult;
    }

    @PostMapping(value = "/book/updateBook")
    public CommonResult updateBook(@RequestBody BookInf book){
        System.out.println();
        int number = bookService.update(book);
        CommonResult addBookCommonResult;
        if (number == 0){
            addBookCommonResult = new CommonResult(404,"default","null");
        }else {
            addBookCommonResult = new CommonResult(200,"success","success");
        }
        return addBookCommonResult;
    }

    @PostMapping(value = "/book/deleteBook/{id}")
    public CommonResult deleteBook(@PathVariable("id") int id){
        int number = bookService.deleteBook(id);
        CommonResult delcommonResult;
        if (number == 0){
            delcommonResult = new CommonResult(404,"default","null");
        }else {
            delcommonResult = new CommonResult(200,"success","success");
        }
        return delcommonResult;
    }

    @PostMapping(value = "/book/index")
    public String index() {
        return "index";
    }

}
           

因为跟着学习视频做了对数据的简单封装:CommonResult 。

浏览器不能主动对服务端发送请求,这里要用测试工具进行。