Eureka - service registration and discovery

Introduction to Eureka

Eureka is a service discovery framework developed by Netflix. It is a REST-based service. It is mainly used to locate middle-tier services running in the AWS domain to achieve load balancing and middle-tier service failover.

Eureka consists of two components: Eureka Server and Eureka Client:

  • Eureka Server provides service registration service. After each node is started, it will be registered in Eureka Server, so that the information of all available service nodes will be stored in the service registry in Eureka Server, and the information of service nodes can be seen intuitively in the interface .
  • Eureka Client is a java client that simplifies interaction with Eureka Server. The client is also a built-in load balancer that uses a round-robin load algorithm.

After the application starts, it will send a heartbeat to Eureka Server. The default period is 30 seconds. If Eureka Server does not receive a heartbeat from a node within multiple heartbeat cycles, Eureka Server will send this service node from the service registry. Removed (default 90 seconds).

Ready to work

  • Step 1:
    Create a table tb_order
    in the database whyorder Create a table tb_user in the database whyuser
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

DROP TABLE IF EXISTS `tb_order`;
CREATE TABLE `tb_order`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '订单id',
  `user_id` bigint(20) NOT NULL COMMENT '用户id',
  `name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '商品名称',
  `price` bigint(20) NOT NULL COMMENT '商品价格',
  `num` int(10) NULL DEFAULT 0 COMMENT '商品数量',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `username`(`name`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 109 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

INSERT INTO `tb_order` VALUES (101, 1, 'Apple 苹果 iPhone 12 ', 5999, 1);
INSERT INTO `tb_order` VALUES (102, 2, '雅迪 yadea 新国标电动车', 2099, 1);
INSERT INTO `tb_order` VALUES (103, 3, '骆驼(CAMEL)休闲运动鞋女', 439, 1);
INSERT INTO `tb_order` VALUES (104, 4, '小米10 双模5G 骁龙865', 3599, 1);
INSERT INTO `tb_order` VALUES (105, 5, 'OPPO Reno3 Pro 双模5G 视频双防抖', 2999, 1);
INSERT INTO `tb_order` VALUES (106, 6, '美的(Midea) 新能效 冷静星II ', 5449, 1);
INSERT INTO `tb_order` VALUES (107, 2, '西昊/SIHOO 人体工学电脑椅子', 799, 1);
INSERT INTO `tb_order` VALUES (108, 3, '梵班(FAMDBANN)休闲男鞋', 319, 1);

SET FOREIGN_KEY_CHECKS = 1;
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '收件人',
  `address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `username`(`username`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 109 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

INSERT INTO `tb_user` VALUES (1, '张三', '浙江省杭州市');
INSERT INTO `tb_user` VALUES (2, '李四', '浙江省宁波市');
INSERT INTO `tb_user` VALUES (3, '王五', '浙江省温州市');
INSERT INTO `tb_user` VALUES (4, '赵六', '浙江省台州市');
INSERT INTO `tb_user` VALUES (5, '田七', '浙江省金华市');
INSERT INTO `tb_user` VALUES (6, '赵八', '浙江省嘉兴市');

SET FOREIGN_KEY_CHECKS = 1;

  • Step 2:
    Quickly create two springboot projects,
    one is privoder-server (service provider) and
    the other is consumer-server (service consumer).
    Here I use the image address of Alibaba Cloud
    insert image description here

  • Step 3: Introduce relevant dependencies

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.2.0</version>
</dependency>
<!-- lombok -->
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<version>1.18.20</version>
</dependency>
  • Step 3:
    Quickly create entity classes, Dao layer, Service layer and Controller
//实体类(两个项目的实体类一样)
//----------订单类----------
@Data
public class Order {
    
    
    private Long id;
    private Long price;
    private String name;
    private Integer num;
    private Long userId;
    private User user;
}
//----------用户类----------
@Data
public class User {
    
    
    private Long id;
    private String username;
    private String address;
}
//---------------Dao层代码(privider-serve)---------------
@Mapper
public interface UserMapper {
    
    
    @Select("select * from tb_user where id = #{id}")
    User selectById(Long id);
}
//---------------Service层代码(privider-serve)---------------
@Service
public class UserService {
    
    
    @Autowired
    private UserMapper userMapper;

    public User queryUserById(Long id){
    
    
        User user = userMapper.selectById(id);
        return user;
    }
}
//---------------Cintroller(privider-serve)---------------
@Controller
@RequestMapping("/user")
public class UserController {
    
    
    @Autowired
    private UserService userService;

    @RequestMapping("/{id}")
    @ResponseBody
    public User queryUser(@PathVariable("id") Long userId){
    
    
        User user = userService.queryUserById(userId);
        return user;
    }
}
//---------------Dao层代码(consumer-serve)---------------
@Mapper
public interface OrderMapper {
    
    
    @Select("select * from tb_order where id = #{id}")
    Order selectById(Long id);
}
//---------------Service层代码(consumer-serve)---------------
@Service
public class OrderService {
    
    
    @Autowired
    private OrderMapper orderMapper;

    public Order queryOrderById(Long id){
    
    
        Order order = orderMapper.selectById(id);
        return order;
    }
}
//---------------Controller(consumer-serve)---------------
@Controller
@RequestMapping("/order")
public class OerderController {
    
    
    @Autowired
    private OrderService orderService;

    @RequestMapping("/{id}")
    @ResponseBody
    public Object queryOrder(@PathVariable("id") Long orderId){
    
    
        Order order = orderService.queryOrderById(orderId);
        return order;
    }
}
  • Step 4: Configure the springboot configuration file
#provider-server配置文件
server:
  port: 8081
spring:
  datasource:
  	#参数是关于时区和字符集的
    url: jdbc:mysql://127.0.0.1:3306/whyuser?serverTimezone=UTC&useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8
    username: root
    password: why0417
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  type-aliases-package: com.why.pojo
  configuration:
    map-underscore-to-camel-case: true
logging:
  level:
    com.why: debug
  pattern:
    dateformat: MM-dd HH:mm:ss:SSS
#consumer-server配置文件
server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/whyorder?serverTimezone=UTC&useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8
    username: root
    password: why0417
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  type-aliases-package: com.why.pojo
  configuration:
    map-underscore-to-camel-case: true
logging:
  level:
    com.why: debug
  pattern:
    dateformat: MM-dd HH:mm:ss:SSS

Build Eureka registry

  • Step 1: Quickly create a springboot project
    insert image description here

  • Step 2: Import eureka dependencies

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>        
</dependency>
  • Step 3: Add the @EnableEurekaServer annotation
/*Eureka自动装配*/
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
    
    

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

Step 4: Configure the springboot configuration file

server:
  port: 8088

spring:
  application:
    #eureka的服务名称
    name: eurekaserver

eureka:
  client:
    service-url:
      #eureka的地址信息
      defaultZone: http://localhost:8088/eureka

Start the project and access Eureka
insert image description here

service registration

  • Step 1: Add the eureka-client dependency to the service provider project
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
	<version>2.2.6.RELEASE</version>
</dependency>
  • Step 2: Configure the eureka address in the application.yml configuration file
spring:
  application:
  	#配置服务名称
    name: userservice

eureka:
  client:
    service-url:
      #eureka地址信息
      defaultZone: http://localhost:8088/eureka

  • Step 3: Start the service provider multiple times to simulate multi-instance deployment
    insert image description here
    Modify the port to avoid port conflicts-Dserver.port=8082
    insert image description here

service discovery

  • Step 1: Add the eureka-client dependency to the service consumer project
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
	<version>2.2.6.RELEASE</version>
</dependency>
  • Step 2: Configure the eureka address in the application.yml configuration file
spring:
  application:
  	#配置服务名称
    name: userservice

eureka:
  client:
    service-url:
      #eureka地址信息
      defaultZone: http://localhost:8088/eureka
  • Step 3: Register RestTemplate (a tool provided by Spring to send http requests)
//写在配置类中(或者启动类,因为@SpringBootApplication是复合注解它包括@SpringBootConfiguration注解)
//注入依赖
@Bean
@LoadBalanced //负载均衡
public RestTemplate restTemplate() {
    
    
	return new RestTemplate();
}
  • Step 4: Modify the Service layer code
@Service
public class OrderService {
    
    
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RestTemplate restTemplate;

    public Order queryOrderById(Long id){
    
    
        Order order = orderMapper.selectById(id);
        //远程调用
        //String url = "http://localhost:8081/user/"+order.getUserId();
        //用服务名代替IP端口
        String url = "http://userservice/user/"+order.getUserId();
        //发送http请求
        User user = restTemplate.getForObject(url, User.class);
        order.setUser(user);
        return order;
    }
}

test

Start all services
insert image description here
Register to eureka instance
insert image description here
Access order
insert image description here

Guess you like

Origin blog.csdn.net/m0_60117382/article/details/123890601