搭建springcloud项目——简单明了(三)

本文涉及的产品
应用型负载均衡 ALB,每月750个小时 15LCU
传统型负载均衡 CLB,每月750个小时 15LCU
网络型负载均衡 NLB,每月750个小时 15LCU
简介: 本文继续讲解搭建springcloud项目的过程。

接上文:搭建springcloud项目——简单明了(二)


UserServiceImpl类

42.png

@Service
@Transactional
public class UserServiceImpl implements UserService {
    //注入用户Mapper
    @Autowired
    private UserMapper userMapper;
    //查询所有用户
    public List<User> getAllUsers() {
        return this.userMapper.getAllUsers();
    }
    //删除用户
    public void deleteUser(Integer id) {
        System.out.println("删除了id为"+id+"的用户");
        this.userMapper.delete(id);
    }


UserService接口


public interface UserService {
    //查询所有
    List<User> getAllUsers();
    //删除数据
    void deleteUser(Integer id);
}


UserController类


43.png


@RestController
@RequestMapping("/user")
public class UserController {
    //注入用户Service
    @Autowired
    private UserService userService;
    //查询所有用户
    @RequestMapping("/userList")
    public List<User> getAllUsers(){
        List<User> list = this.userService.getAllUsers();
        return list;
    }
    //删除用户
    @RequestMapping("/delete/{id}")
    public void delete(@PathVariable Integer id){
        this.userService.deleteUser(id);
    }


然后检查eureka-user的Controller


44.png


然后按顺序分别启动eureka-server、eureka-order、eureka-user


然后访问:http://localhost:8000/findOrdersByUser/1


如图


45.png


这样就证明访问成功了


Ribbon



Ribbon是用来实现负载均衡的


首先我们在eureka-user中Application的@Bean下加注解@LoadBalanced

,加了这个注解后RestTemplate就具有了负载均衡能力。


46.png


然后将eureka-user中的UserController进行如下修改


47.png


我们将之前的“主机地址+端口号”变成了实例名称


在order中写一个工具类


48.png


@Configuration
public class ServiceInfoUtil implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {
    /**
     * 声明event对象,该对象用于获取运行服务器的本地端口
     */
    private static EmbeddedServletContainerInitializedEvent event;
    public void onApplicationEvent(
            EmbeddedServletContainerInitializedEvent event){
        ServiceInfoUtil.event = event;
    }
    /**
     * 获取端口号
     */
    public static int getPort(){
        int port = event.getEmbeddedServletContainer().getPort();
        return port;
    }


然后在userList接口中写一个输出,这是用来输出端口号


49.png


然后将eureka-order先启动一次,再把端口号该为7901再启动一次


50.png


可以看到启动了两个order服务


然后我们访问http://localhost:8000/findOrdersByUser/1


52.png


我们多访问几次,然后看输出


53.png


54.png


我们可以看到,这两个不同端口的order都访问到了,证明Ribbon实现了负载均衡机制。


eureka-user-hystrix



接下来我们写hystrix模块,简单了来说就是熔断器模块,因为在系统中例如c服务调用b服务,然后b服务调用a服务,假如a服务出现问题,那么会导致b服务出现问题,然后再导致c服务出现问题,最终整个系统全部瘫痪,为了解决这个问题就出现了熔断器。


1、新建eureka-user-hystrix模块,步骤和上面的其他模块一样,pom.xml中添加如下配置。


55.png


 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <!--Hystrix依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>


yml文件如下


57.png


server:
  port: 8030
eureka:
  instance:
    prefer-ip-address: true
  client:
    service-rul:
      defaultZone: http://localhost:8761/eureka/
spring:
  application:
    name: eureka-user-hystrix


新建启动类


58.png


@SpringBootApplication
@EnableCircuitBreaker
@EnableEurekaClient
public class Application {
  public static void main(String [] args){
    SpringApplication.run(Application.class, args);
  }
  @Bean
  @LoadBalanced
  public RestTemplate restTemplate(){
    return new RestTemplate();
  }
}


新建UserController,代码中的fallbackInfo方法就是在指定的服务出现问题不能访问的时候就会走这个方法,当指定的服务问题解决以后又会自动再访问指定的访问,这里是自动熔断与连接的。


59.png


@RestController
public class UserController {
    @Autowired
    private RestTemplate restTemplate;
    /**
     * 查找与用户相关的订单
     */
    @GetMapping("/findOrdersByUser/{id}")
    @HystrixCommand(fallbackMethod = "fallbackInfo")
    public String findOrdersByUser(@PathVariable String id){
        return this.restTemplate.getForObject("http://eureka-order/user/userList", String.class);
    }
    /**
     * 返回信息方法
     */
     public String fallbackInfo(@PathVariable String id){
         return "服务不可用,请稍后再试!";
     }
}


现在我们来依次启动项目,order启动两个,分别为7900和7901


启动后访问http://localhost:8761/ 如下图证明启动成功


60.png


然后访问http://localhost:8030/findOrdersByUser/1 如下图


61.png


然后我们就多访问几次,发现访问正常,而且负载也正常


62.png


63.png


这个时候我们停掉7901的服务


然后我们再次刷新之前的路径,当负载到7901的接口的时候出现下图证明成功


64.png


然后我们再启动7901服务后,再次访问就不会出现上图情况,证明我们熔断器配置成功。


gateway-zuul



接下来我们创建zuul(网关)模块,网关可以用来执行认证、动态路由、安全和动态响应等功能,这里主要讲一下动态路由。


新建gateway-zuul,pom.xml配置如下


65.png


<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>


yml配置如图


66.png


新建启动类


67.png


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


然后我们依次启动注册中心(eureka-server)、服务提供者(eureka-order)、网关服务(gateway-zuul)


然后我们访问 http://localhost:7900/order/1


出现下图证明成功


70.png


config-server



接下来我们创建配置模块,因为我们以后可能随着业务越来越大,我们会从单体系统升级为分布式系统,但是我们每一个模块都有一个配置文件,这样我们要修改一个模块的配置文件,就需要找到该模块的所有文件,一个一个修改。









相关实践学习
SLB负载均衡实践
本场景通过使用阿里云负载均衡 SLB 以及对负载均衡 SLB 后端服务器 ECS 的权重进行修改,快速解决服务器响应速度慢的问题
负载均衡入门与产品使用指南
负载均衡(Server Load Balancer)是对多台云服务器进行流量分发的负载均衡服务,可以通过流量分发扩展应用系统对外的服务能力,通过消除单点故障提升应用系统的可用性。 本课程主要介绍负载均衡的相关技术以及阿里云负载均衡产品的使用方法。
相关文章
|
3天前
|
前端开发 Java Nacos
🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
本文介绍了如何使用Spring Cloud Alibaba 2023.0.0.0技术栈构建微服务网关,以应对微服务架构中流量治理与安全管控的复杂性。通过一个包含鉴权服务、文件服务和主服务的项目,详细讲解了网关的整合与功能开发。首先,通过统一路由配置,将所有请求集中到网关进行管理;其次,实现了限流防刷功能,防止恶意刷接口;最后,添加了登录鉴权机制,确保用户身份验证。整个过程结合Nacos注册中心,确保服务注册与配置管理的高效性。通过这些实践,帮助开发者更好地理解和应用微服务网关。
21 0
🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
|
17天前
|
网络协议 Java Shell
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
53 7
|
1月前
|
人工智能 安全 Java
AI 时代:从 Spring Cloud Alibaba 到 Spring AI Alibaba
本次分享由阿里云智能集团云原生微服务技术负责人李艳林主讲,主题为“AI时代:从Spring Cloud Alibaba到Spring AI Alibaba”。内容涵盖应用架构演进、AI agent框架发展趋势及Spring AI Alibaba的重磅发布。分享介绍了AI原生架构与传统架构的融合,强调了API优先、事件驱动和AI运维的重要性。同时,详细解析了Spring AI Alibaba的三层抽象设计,包括模型支持、工作流智能体编排及生产可用性构建能力,确保安全合规、高效部署与可观测性。最后,结合实际案例展示了如何利用私域数据优化AI应用,提升业务价值。
194 4
|
2月前
|
存储 JSON 前端开发
【Spring项目】表白墙,留言板项目的实现
本文主要介绍了表白墙项目的实现,包含前端和后端代码,以及测试
|
2月前
|
JSON 前端开发 Java
|
2月前
|
缓存 前端开发 Java
【Spring】——SpringBoot项目创建
SpringBoot项目创建,SpringBootApplication启动类,target文件,web服务器,tomcat,访问服务器
|
2月前
|
消息中间件 监控 Java
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
51 6
|
2月前
|
负载均衡 Java 开发者
深入探索Spring Cloud与Spring Boot:构建微服务架构的实践经验
深入探索Spring Cloud与Spring Boot:构建微服务架构的实践经验
215 5
|
2月前
|
Java 关系型数据库 MySQL
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
84 5
|
2月前
|
缓存 监控 Java
如何将Spring Boot应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot应用程序部署到Pivotal Cloud Foundry (PCF)
65 5