SpringCloud

文章目录

  • *
    • pom.xml
  • Eureka
    • pom.xml
    • 启动类
    • application.xml
  • service
    • pom.xml
    • 启动类
    • application.yml
  • feign
    • hystrix支持
    • pom.xml
    • Client
    • FallbackClass
    • 调用Client模块
      • 启动类
      • RequestInterceptor
  • Gateway
    • pom.xml
    • application.yml
    • 全局过滤器
  • Amqp
    • pom.xml
    • application.yml
    • component
    • config
  • 配置中心
    • ConfigApplication
      • pom.xml
      • Application.java
      • application.yml
    • 获取配置
      • pom.xml
      • application.yml
      • Controller

*

pom.xml

<!--springBoot项目要继承spring-boot-starter-parent-->
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version></version>
</parent>

    <dependencyManagement>
        <dependencies>
            <!--springCloud项目限定依赖版本,防止依赖冲突,官网有生成,随便选一个cloud依赖-->
            <!--添加后<groupId>org.springframework.cloud</groupId>可以不写version-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version></version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
          <!--注册到eureka的服务要依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

Eureka

pom.xml

    <dependencies>
        <!--@EnableEurekaServer自动导包倒的没有'-starter',会有包冲突,依赖有spring-boot-starter-web-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>

启动类

//应用为Eureka服务
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaApplication.class,args);
    }
}

application.xml

server:
  #服务端口,集群时同服务名不同端口
  port: ${port:8761}
spring:
  application:
  	#Eureka中的服务名
    name: eureka-server
eureka:
  client:
    service-url:
      defaultZone: http://localhost:${potr:8761}/eureka
    #拉取服务,集群时用
    fetch-registry: ${fetch:false}
    #注册到eureka,集群时用
    register-with-eureka: ${register:false}

service

pom.xml

其他依赖按SpringBoot

<!--@EnableDiscoveryClient自动导的包不能注册到eureka服务-->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

启动类

//注册到Eureka服务
@EnableDiscoveryClient
//全局属性类,controller不用再注解直接@Autowired
@EnableConfigurationProperties({Propoties.class})
@SpringBootApplication
public class ServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServerApplication.class, args);
    }
}

application.yml

server:
  port: ${port:port}
spring:
  application:
    name: service-name
eureka:
  client:
    service-url:
      #多个Eureka服务用','
      defaultZone: http://localhost:8761/eureka

feign

hystrix支持

feign: 
  hystrix:
  enabled: true

pom.xml

不用启动,调用的模块引用feign模块依赖

		<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-openfeign-core</artifactId>
            <version></version>
        </dependency>
        <!--调用时找不到服务-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
            <version></version>
        </dependency>
           <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-slf4j</artifactId>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-core</artifactId>
        </dependency>

Client

传入实体类实现类参数要@RequestBody,数据通过json传递

@FeignClient(value = "service-name", fallback = ServerClientFallback.class /*服务降级类*/)//通过服务名在Eureka调用服务
public interface ServerClient {
    @GetMapping("/")//访问service的路径
    String function(@RequestParam("")/*传String一定要加,接收不到*/ String s);
}

FallbackClass

@Component
public class ServerClientFallback implements ServerClient {
	//重写降级处理方法
	@Override
	String function(){}

调用Client模块

启动类

@EnableFeignClients(basePackages = {"包"})//扫描feign接口,默认扫当前包下,包路径不一致要配置
@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class,args);
    }
    //需要手动注入
	@Bean
    @ConditionalOnMissingBean
    public HttpMessageConverters messageConverters(ObjectProvider<HttpMessageConverter<?>> converters) {
        return new HttpMessageConverters(converters.orderedStream().collect(Collectors.toList()));
    }
}

RequestInterceptor

发送feign请求前进入RequestInterceptor

@Component
public class Interceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header("","");
    }
}

Gateway

pom.xml

<!--有spring-boot-starter-web包-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>

application.yml

spring:
  application:
    name: gateway
  cloud:
    gateway:
      routes:
        - id: comsumer-route
          #lb://{Eureka中的服务名}
          uri: lb://consumer
          #要访问的地址 = lb://consumer/**
          predicates:
            - Path=/**
          filters:
            #在访问的地址前添加前缀 /prefixPath/**
            - PrefixPath=/prefixPath
            #去除访问地址前缀
            - StripPrefix=1
      default-filters:
      	#依赖spring-cloud-starter-circuitbreaker-reactor-resilience4j
        - name: CircuitBreaker #旧版springCloud是Hystrix
          args:
            name: fallback
            #fallback路径
            fallbackUri: forward:/fallback
        #限制用户每分钟请求次数
        #依赖spring-boot-starter-data-redis-reactive
        - name: RequestRateLimiter
          args:
            redis-rate-limiter.replenishRate: 10
      #ajax跨域设置
      globalcors:
        cors-configurations:
          '[/**]':
         	#允许跨域地址
            allowedOrigins:
              - "url"
            #允许跨域请求方法
            allowedMethods:
              - GET
              - POST

全局过滤器

@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //exchange可以获取ServerHttpRequest和ServerHttpResponse对象
        //添加请求头用exchange.getRequest().mutate().header(),exchange.getRequest().getHeaders().add()会找不到
        //修改request后要修改exchange才生效
        exchange = exchange.mutate().request(request).build();
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //越小越先执行
        return 0;
    }
}

Amqp

pom.xml

		
        
            org.springframework.boot
            spring-boot-starter-amqp
        

application.yml

spring:
  rabbitmq:
      host: $[host}
      port:${port}
      username: ${username}
      password: $[pasword}
      virtual-host:${virtualHosts}

component

@Autowired
AmqpTemplate amqpTemplate;

/**
	发送消息
	var1: 交换机名称,使用默认交换机设置""
	var2:路由key,不是DIRECT模式时绑定队列,没有写"",可以多段*.*.*(*匹配一个,#匹配多个)
	var3:消息内容
*/
void function(){
        amqpTemplate.convertAndSend(String var1, String var2, Object var3);
 }

//接收消息
@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "queueName",durable = "true"),
    exchange = @Exchange(value = "exchangeName"),
    key = {"routingKey"}))
public void function(String msg){}

config

//转换成json传输
@Configuration 
public class RabbitConfig { 
	@Bean 
	public Jackson2JsonMessageConverter messageConverter(){ 
		return new Jackson2JsonMessageConverter();
	} 
}

配置中心

ConfigApplication

pom.xml

		<!--配置改变后仓库webhook发送到服务monitor/-->
		 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-monitor</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-config-server</artifactId>
        </dependency>

Application.java

@EnableConfigServer //开启配置中心服务

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

application.yml

spring:
  cloud:
    config:
      server:
        git:
          uri: git仓库地址
  rabbitmq:
      host: $[host}
      port:${port}
      username: ${username}
      password: $[pasword}
     

获取配置

pom.xml

 <!--消息总线-->
 		<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>

application.yml

spring:
  application:
  	#自动获取${service-name}.yml
    name: ${service-name}
  config:
    import: optional:configserver:http://ip:port
  #实时更新配置要用
  rabbitmq: 
    host: ${host:192.168.58.167}
    port: ${port:5672}
    username: zybe
    password: zybe

Controller

@RefreshScope //收到刷新消息后刷新有注解的类
public class ConsumerController {}

你可能感兴趣的:(spring,cloud,eureka,微服务)