栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

从零搭建spring cloud微服务架构(基于springboot)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从零搭建spring cloud微服务架构(基于springboot)

    使用springboot构建商品服务
    1.1IDEA新建Item-Service项目,引入web、jpa、mysq驱动、junit测试包


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.2
         
    
    com.yf.cn
    item-service
    0.0.1-SNAPSHOT
    item-service
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            junit
            junit
            4.12
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



  1.2修改resources目录下的application.properties为application.yml,并添加对应的配置
server:
  port: 7900
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/jpa?serverTimezone=GMT%2B8
    username: root
    password: 123456
  jpa:
    database: mysql
    hibernate:
      ddl-auto: update
    show-sql: true
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
1.3在主包结构com.yf.cn下新建entity包,并新建Item实体类
package com.yf.cn.entity;

import javax.persistence.*;

@Entity
@Table(name="t_item")
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column
    private String name;
    @Column
    private String url;
}

1.4在主包结构com.yf.cn下新建repository包,并新建ItemRepository接口,并继承(extends)Repository(org.springframework.data.repository.Repository)接口
package com.yf.cn.repository;

import com.yf.cn.entity.Item;
import org.springframework.stereotype.Repository;


@Repository
public interface ItemRepository extends org.springframework.data.repository.Repository {

}

1.5编写测试类,测试Item新增
package com.yf.cn.repository;

import com.yf.cn.entity.Item;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class TestItem {
    @Autowired
    private ItemRepository itemRepository;
    @Test
    public void testSaveItem(){
        Item item = new Item();
        item.setName("尿不湿");
        item.setUrl("http://123.jpg");
        itemRepository.save(item);

    }
}

1.6在主包结构com.yf.cn下新建controller包,并新建ItemController
package com.yf.cn.controller;

import com.yf.cn.entity.Item;
import com.yf.cn.repository.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
@RequestMapping("/item/")
public class ItemController {
    @Autowired
    private ItemRepository itemRepository;
    @RequestMapping("getById/{id}")
    public Optional getById(@PathVariable Long id){
        Optional item = itemRepository.findById(id);
        return item;
    }

}

1.7在浏览器输入访问链接http://localhost:7900/item/getById/6,可以看到已经能正常查询获取到数据


2. 使用spring构建订单微服务
2.1新建订单微服务Order-service,引入web模块



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.2
         
    
    com.yf.cn
    order-service
    0.0.1-SNAPSHOT
    order-service
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



2.2修改resources目录下的application.properties为application.yml,并添加对应的配置
server:
  port: 7901
2.3编写OrderController进行item-service服务调用(RestTemplate)
package com.yf.cn.controller;

import com.yf.cn.entity.Item;
import org.springframework.beans.factory.annotation.Autowired;
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;

@RestController
@RequestMapping("/order/")
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;
    @RequestMapping("getById/{id}")
    public Item getItemByItemService(@PathVariable Long id){
        Item item =  restTemplate.getForObject("http://localhost:7900/item/getById/"+id,Item.class);
        return item;
    }
}

2.4浏览器输入访问链接查看执行结果


2.5调用item-service服务成功

订单微服务调用商品微服务(spring cloud)
3.1细心的读者会发现,在上面订单服务调用商品服务,服务的地址是写死在订单服务中的,这种应硬编码在商品的部署环境发生变化后,需要在订单服务的代码中修改调佣路径;如果商品微服务存在多个,在订单微服务中路径又该怎么写呢?带着这些疑问我们来了解spring cloud,spring cloud将带领你逐一解答这些疑问。
3.2spring cloud 通过服务注册和服务发现机制来完成

3.3由上图可以看出
3.3.1服务提供者将服务注册到注册中心
3.3.2服务消费者通过注册中心查找服务
3.3.3查找到服务后进行调用(无需硬编码解决方案)
3.3.4服务的喜爱费者与服务注册中心保持心跳连接,一旦服务提供者的地址发生变更时,注册中心会通知服务消费者
3.4注册中心:Eureka
spring 提供了多种注册中心的支持,如eureka、consul、Zookeeper。

3.5原理:

Eureka包含两个组件:Eureka Server和Eureka Client

Eureka提供服务注册服务,各个节点启动后会在Eureka中进行注册,这样EurekaServer中的服务注册表将会存储所有可用服务节点信息,服务节点的信息可以在界面直观看到

Eureka Client是一个java客户端,用于简化和Eureka Server的交互,客户端内置一个使用轮训负载算法的负载均衡器

在应用启动后,将会想Eureka Server发送心跳,默认周期为30秒,如果Eureka Server在多个周期没有收到某个节点的心跳,Eureka Server将会从服务注册表中把这个节点移除(默认90s)

Eureka Server之间通过复制的方式同步数据,Eureka 还提供了客户端缓存机制,即使所有的Eureka Server都挂掉,客户端依然可以利用缓存中的信息消费其他服务的ApI。综上Eureka通过心跳检查、客户端缓存机制确保了系统的高可用性、灵活性和可伸缩性。
3.6创建Eureka Server服务,引入spring cloud坐标



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.2
         
    
    com.yf.cn
    eureka-server
    0.0.1-SNAPSHOT
    eureka-server
    Demo project for Spring Boot
    
        1.8
        2021.0.0
    
    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    
    
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-server
        
    


    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



3.6.1修改该resource下的application.properties文件为application.yml,并进行端口和服务地址等配置
###服务端口号
server:
  port: 8101

###服务名称
spring:
  application:
    name: app-eureka-server

eureka:
  instance:
    #注册中心地址
    hostname: 127.0.0.1
  ###客户端调用地址
  client:
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:8101/eureka/
    ###是否将自己注册到Eureka服务中,因为该应用本身就是注册中心,不需要再注册自己(集群的时候为true)
    register-with-eureka: false
    ###是否从Eureka中获取注册信息,因为自己为注册中心,不会在该应用中的检索服务信息
    fetch-registry: false


3.6.2在启动类中添加@EnableEurekaServer,启动服务,在浏览器输入ip和端口查看状态,至此注册中心服务已经搭建成功


3.7将商品服务和订单服务注册到注册服务中心
3.7.1修改商品服务的pom文件,添加spring cloud和Eureka Client坐标



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.2
         
    
    com.yf.cn
    item-service
    0.0.1-SNAPSHOT
    item-service
    Demo project for Spring Boot
    
        1.8
        2021.0.0
    
    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    
    
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            junit
            junit
            4.12
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



3.7.2在application.yml中添加注册的服务名称和注册的服务地址


yml最终的配置为:

server:
  port: 7901
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/jpa?serverTimezone=GMT%2B8
    username: root
    password: 123456
  jpa:
    database: mysql
    hibernate:
      ddl-auto: update
    show-sql: true
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
  application:
    name: app-item
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8101/eureka
    register-with-eureka: true
    fetch-registry: true

3.7.3在启动类中添加@EnableEurekaClient
package com.yf.cn;

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

@SpringBootApplication
@EnableEurekaClient
public class ItemServiceApplication {

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

}

3.7.4启动item-service在注册中心查看,可以看到app-item已经注册到了服务中心


3.7.5注册订单服务到注册中心,修改订单微服务pom文件,添加spring cloud和Eureka Client坐标



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.2
         
    
    com.yf.cn
    order-service
    0.0.1-SNAPSHOT
    order-service
    Demo project for Spring Boot
    
        1.8
        2021.0.0
    
    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



3.7.6修改yml配置文件,添加注册的服务名称和注册的服务中心的地址

3.7.7修改启动类,在RestTemplate类上方添加@LoadBalanced注解(必须添加),启动类添加@EnableEurekaClient注解,启动服务

3.7.8修改OrderController改为由服务名称调用商品服务

package com.yf.cn.controller;

import com.yf.cn.entity.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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;

@RestController
@RequestMapping("/order/")
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;
    @Value("${server-name.item}")
    private String itemServerUrl;
    @RequestMapping("getById/{id}")
    public Item getItemByItemService(@PathVariable Long id){
        Item item =  restTemplate.getForObject(itemServerUrl+"item/getById/"+id,Item.class);
        return item;
    }
}


发现依然可以正常调用,至此微服务架构搭建完成。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/703793.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号