SpringCloud实例---电影购票

前言

最近分享了一些springcloud微服务相关的文章,一些小伙伴在后台私信笔者,问能否出一个springcloud项目的教程。当时看到私信后,也很重视,话不多说,下面我们就来看如何通过springcloud来进行操作。

功能概述:

功能:

服务提供端:能够增加电影;能够获取所有电影;能够按照名称查询电影

服务消费端: 能够查询所有电影;能够购票

Zuul网关:对请求进行过滤,对符合要求的请求进行放行,对不符合要求的请求进行拦截

Config-Server:服务提供端与消费端的配置文件,均从gitee上获取,而不是本地配置文件

EurekaServer:服务注册中心

其他:通过feign实现负载均衡,通过hystrix进行服务熔断

项目结构:

 Common:公共的部分,相当于WEB开发过程的抽取

Config-Server:配置了gitee的地址,服务提供与消费端均通过Config-Server来获取自身配置文件

Eureka-Movie:服务提供端,提供了查询,新增等相关服务

Eureka-User:服务消费端

Eureka-Server:服务注册中心

SpringCloud-Movie

总体的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example</groupId>
  <artifactId>SpringCloud-Movie</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <name>SpringCloud-Movie</name>
  <url>http://maven.apache.org</url>
  <modules>
    <module>Common</module>
    <module>Eureka-Server</module>
    <module>Eureka-User</module>
    <module>Eureka-Movie</module>
    <module>Zuul-GateWay</module>
      <module>Config-Server</module>
  </modules>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.5.RELEASE</version>
  </parent>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring.cloud.version>Hoxton.SR3</spring.cloud.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>2.3.1</version>
    </dependency>
  </dependencies>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>Hoxton.SR3</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
</project>

Common

主要就是进行了一个实体类的编写,因为需要连接数据库,并且消费端和服务端都需要连接数据库,为了避免多次定义实体,故通过一个Common来定义实体类,并将其集成到消费端与服务端

Movie.class

package org.example;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @ClassName Movie
 * @Author 23
 * @Date 2024/7/15 9:25
 * @Version 1.0
 * @Description TODO
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Movie {
    private Integer id;
    private String name;
    private Integer price;
    private String start_time;
    private String end_time;
}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.example</groupId>
        <artifactId>SpringCloud-Movie</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>Common</artifactId>
    <packaging>jar</packaging>

    <name>Common</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

Config-Server

服务的配置中心,消费端与服务端的配置文件都需要通过Config-Server来进行拉取

服务启动类

package org.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.config.server.EnableConfigServer;

/**
 * @ClassName ConfigStart
 * @Author 23
 * @Date 2024/7/15 11:01
 * @Version 1.0
 * @Description TODO
 **/
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@EnableConfigServer // 表明这是一个config服务端
public class ConfigStart {
    public static void main(String[] args) {
        SpringApplication.run(ConfigStart.class,args);
    }
}

application.yml

server:
  port: 40010
spring:
  application:
    name: config-server
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/*****/spring-cloud-config.git
          username:*
          password: *

这里的git要用自己的,然后消息队列可以不用,笔者这里用了是为了方便配置文件的动态自动刷新。 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.example</groupId>
        <artifactId>SpringCloud-Movie</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>Config-Server</artifactId>
    <packaging>jar</packaging>

    <name>Config-Server</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <!-- 导入spring cloud config服务端的包 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-bus-amqp</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.60</version>
    </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
</dependencies>
</project>

Eureka-Movie

服务启动类

package org.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @ClassName MovieStart
 * @Author 23
 * @Date 2024/7/15 9:48
 * @Version 1.0
 * @Description TODO
 **/
@SpringBootApplication
@EnableDiscoveryClient
public class MovieStart {
    public static void main(String[] args) {
        SpringApplication.run(MovieStart.class,args);
    }
}

Mapper层

package org.example.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.example.Movie;

import java.util.List;

@Mapper
public interface MovieMapper {
    @Insert("INSERT INTO `manager`.`movie`(`name`, `price`, `start_time`, `end_time`) VALUES ( #{name}, #{price}, #{start_time}, #{end_time})")
    void insert(Movie movie);
    @Select("select * FROM `manager`.`movie`")
    List<Movie> SelectAll();
    @Select("select * FROM `manager`.`movie` where `name`=#{name}")
    List<Movie> SelectByName(@Param("name") String name);
}

Controller层

package org.example.Controller;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.example.Movie;
import org.example.mapper.MovieMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName SelectController
 * @Author 23
 * @Date 2024/7/15 10:50
 * @Version 1.0
 * @Description TODO
 **/
@RestController
@RequestMapping("/Select")
public class SelectController {
    @Autowired
    MovieMapper movieMapper;
    @Value("${server.port}")
    private String port;
    @GetMapping("/Test/{id}")
    public List<Movie> getMovieById(@PathVariable("id") Integer id){
        return Arrays.asList(new Movie(1,"大圣归来",100,"17:30","19:30"));
    }
    @PostMapping("/add")
    public void insert(@RequestBody Movie movie){
        movieMapper.insert(movie);
    }
    @GetMapping("/all")
    public List<Movie> list(){
       return movieMapper.SelectAll();
    }
    @GetMapping("/search/{name}")
    public List<Movie> getMovieByName(@PathVariable String name){
        return movieMapper.SelectByName(name);
    }

}

bootstrap.yml

spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/manager?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2b8&allowPublicKeyRetrieval=true
  cloud:
    config:
      uri: http://127.0.0.1:40010
      label: master
      name: application-movie
      profile: dev
      bus:
        id: ${spring.application.name}:${spring.cloud.config.profile}:${random.value}

这里的config当中的uri要配置自己定义的config-server的uri 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.example</groupId>
        <artifactId>SpringCloud-Movie</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>Eureka-Movie</artifactId>
    <packaging>jar</packaging>

    <name>Eureka-Movie</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.example</groupId>
            <artifactId>Common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bus-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>
</project>

Eureka-Server

服务注册中心Eureka

服务启动类

package org.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

/**
 * @ClassName EurekaStart
 * @Author 23
 * @Date 2024/7/15 9:31
 * @Version 1.0
 * @Description TODO
 **/
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@EnableEurekaServer
public class EurekaStart {
    public static void main(String[] args) {
        SpringApplication.run(EurekaStart.class,args);
    }
}

application.yml

server:
  port: 10077
eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: yihttp://${eureka.instance.hostname}:${server.port}/eureka/

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.example</groupId>
        <artifactId>SpringCloud-Movie</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>Eureka-Server</artifactId>
    <packaging>jar</packaging>

    <name>Eureka-Server</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!-- Eureka服务端支持 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>
</project>

Eureka-User

服务消费端

服务启动类

package org.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

/**
 * @ClassName UserStart
 * @Author 23
 * @Date 2024/7/15 9:45
 * @Version 1.0
 * @Description TODO
 **/
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class UserStart {
    public static void main(String[] args) {
        SpringApplication.run(UserStart.class,args);
    }
}

Controller层

package org.example.Controller;

import org.example.Movie;
import org.example.UserClient.UserClient;
import org.example.mapper.Usermapper;
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 org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

/**
 * @ClassName UserController
 * @Author 23
 * @Date 2024/7/15 9:37
 * @Version 1.0
 * @Description TODO
 **/
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private Usermapper usermapper;
    @GetMapping("/movie/{id}")
    public List<Movie> getMovie(@PathVariable("id") Integer id){
        List<ServiceInstance> instances=discoveryClient.getInstances("movie-service");//通过服务的名字去获取服务实例
        ServiceInstance serviceInstance=instances.get(0);//定死只获取第一个服务实例对象
        String ip=serviceInstance.getHost();//获取服务对象ip
        int port=serviceInstance.getPort();//获取获取的实例对象的服务端口号
        System.out.println(port);
        Movie[] movies=restTemplate.getForObject("http://movie-service/Select/Test/"+id,Movie[].class);
        return Arrays.asList(movies);
    }
    @GetMapping("/selectAll")
    public List<Movie> getAllMovie(){
        List<Movie> movies=userClient.selectAllmovies();
        return movies;
    }
    @PostMapping("/byTickets/{name}")
    public List<Movie> ByTickets(@PathVariable("name") String name){
//        List<Movie> movies=restTemplate.getForObject("http://movie-service/Select/search/"+name,List.class);
        List<Movie> movies=userClient.getMovieByname(name);
        if (movies.isEmpty())
        {
            return Arrays.asList(new Movie(500,"当前无该电影",404,"当前无该电影","当前无该电影"));
        }else {
            usermapper.insert(new Movie(null,movies.get(0).getName(),movies.get(0).getPrice(),movies.get(0).getStart_time(),movies.get(0).getEnd_time()));
            return movies;
        }
    }

}

mapper层

主要是一个购票服务

package org.example.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.example.Movie;

@Mapper
public interface Usermapper {
    @Insert("INSERT INTO `manager`.`buymovie`(`name`, `price`, `start_time`, `end_time`) VALUES ( #{name}, #{price}, #{start_time}, #{end_time})")
    void insert(Movie movie);

}

config(工具类)

package org.example.Config;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @ClassName BeanConfig
 * @Author 23
 * @Date 2024/7/15 9:40
 * @Version 1.0
 * @Description TODO
 **/
@Configuration
public class BeanConfig {
    @LoadBalanced//使得restTemplate具有负载均衡能力
    @Bean  //<bean></bean  把new出来的对象放入spring管理
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    @Bean//将IRule交给spring容器
    public IRule myRule(){
        return new RandomRule();
    }

}

UserClient

通过openFeign反向代理,实现服务调用

userClient

package org.example.UserClient;

import org.example.Movie;
import org.example.UserClient.fallback.Moviefallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;
@Component
@FeignClient(value="MOVIE-SERVICE",fallbackFactory = Moviefallback.class)
public interface UserClient {
    @GetMapping("/Select/all")
    List<Movie> selectAllmovies();
    @GetMapping ("/Select/search/{name}")
    List<Movie> getMovieByname(@PathVariable String name);
}

 moviefallback

定义熔断后的返回内容

package org.example.UserClient.fallback;

import feign.hystrix.FallbackFactory;
import org.example.Movie;
import org.example.UserClient.UserClient;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @ClassName Moviefallback
 * @Author 23
 * @Date 2024/7/15 13:03
 * @Version 1.0
 * @Description TODO
 **/
@Component
public class Moviefallback implements FallbackFactory<UserClient> {
    @Override
    public UserClient create(Throwable throwable) {
        return new UserClient() {
            @Override
            public List<Movie> selectAllmovies() {
                throwable.printStackTrace();
                return Arrays.asList(new Movie(404,"服务器异常",404,"服务器异常","服务器异常"));
            }
            @Override
            public List<Movie> getMovieByname(String name) {
                return Arrays.asList(new Movie(500,"服务器异常",404,"服务器异常","服务器异常"));
            }
        };
    }
}

bootstrap.yml

spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/manager?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2b8&allowPublicKeyRetrieval=true
  cloud:
    config:
      uri: http://127.0.0.1:40010
      label: master
      name: application-user
      profile: dev
      bus:
        id: ${spring.application.name}:${spring.cloud.config.profile}:${random.value}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.example</groupId>
        <artifactId>SpringCloud-Movie</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>Eureka-User</artifactId>
    <packaging>jar</packaging>

    <name>Eureka-User</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
        <groupId>org.example</groupId>
        <artifactId>Common</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bus-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>
</project>

Zuul-GateWay

服务启动类

package org.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

/**
 * @ClassName GateWayStart
 * @Author 23
 * @Date 2024/7/15 10:00
 * @Version 1.0
 * @Description TODO
 **/
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
@EnableZuulProxy
public class GateWayStart {
    public static void main(String[] args) {
        SpringApplication.run(GateWayStart.class,args);
    }
}

bootstrap.yml

spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
  cloud:
    config:
      uri: http://127.0.0.1:40010
      label: master
      name: apllication-zuulm
      profile: dev
      bus:
        id: ${spring.application.name}:${spring.cloud.config.profile}:${random.value}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.example</groupId>
        <artifactId>SpringCloud-Movie</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>Zuul-GateWay</artifactId>
    <packaging>jar</packaging>

    <name>Zuul-GateWay</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <!--springboot支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bus-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>
</project>

其他(gitee上拉取的配置内容)

application-user

server:
  port: 10088
spring:
  application:
    name: user-service
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10077/eureka
  instance:
    prefer-ip-address: true
feign:
  hystrix:
    enabled: true
  readTimeout: 1000
  socketTimeout: 1000
  connectTimeout: 1000
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 4000

application-movie

server:
  port: 10099
spring:
  application:
    name: movie-service
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10077/eureka
  instance:
    prefer-ip-address: true

apllication-zuulm

server:
  port: 8898
spring:
  application:
    name: Zuul-GateWay
eureka:
  instance:
    hostname: localhost
  client:
    serviceUrl:
      defaultZone: http://localhost:10077/eureka/
    instance:
      prefer-ip-address: true
zuul:
  routes:
    user.serviceId: user-service
    user.path: /user/**
    order.serviceId: movie-service
    order.path: /movie/**
  ignored-services: "*"
  prefix: "/test"

运行结果

消费端查询所有电影

服务熔断显示结果 

因为篇幅原因,其余功能便不再一一展示,通过对应的端口均可成功实现调用。希望本篇文章对大家理解springcloud微服务的实际应用能够有所帮助,笔者小,中,大厂均有面试经历,坚持每日分享全栈开发知识,希望能够和大家共同进步。 

  • 27
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值