SpringCloud的五大核心组件俊哥,侯哥

乐优项目SpringCloud笔记总结

ly-item 商品的的mapper模块,里面有datasource

ly-cart: 购物车模块

ly-registry: 注册中心服务端,其他的模块都是客户端

ly-api-gateway: 路由网关

ly-feign:远程调用

注册中心Eureka,ly-registry服务端

lyregistry这个Module作为服务端

服务端可以进行配置

server:
  port: 10086

spring:
  application:
    name: ly-registry

eureka:
  client:
    fetch-registry: false
    register-with-eureka: false
    service-url:
      defaultZone: http://localhost:${
    
    server.port}/eureka

  server:
    enable-self-preservation: false #关闭自我保护
    eviction-interval-timer-in-ms: 5000 #每隔5秒进行一次服务列表清理
package com.yunhe;

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

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


使用ly-user作为客户端进行相关的测试:

package com.yunhe;

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

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients  //开启feign功能
public class LyUserApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(LyUserApplication.class,args);
    }
}

加入相关的客户端实现的依赖:

 <!--eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--feign实现远程调用 ly-item-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>

客户端的配置

server:
  port: 10010

spring:
  application:
    name: item-service


  datasource:
    url: jdbc:mysql://localhost:3306/leyou?characterEncoding=UTF-8&useSSL=false
    username: root
    password: roothouzhicong

    hikari:
      maximum-pool-size: 30
      minimum-idle: 10

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka
  instance:
    lease-renewal-interval-in-seconds: 5 #每隔6秒发送一次心跳
    lease-expiration-duration-in-seconds: 10 #10秒不发送就过期
    prefer-ip-address: true
    ip-address: 127.0.0.1
    instance-id: ${spring.application.name}:${server.port}
    
 # 对Ribbon进行配置
item-service: #feign里面负载均衡配置
  ribbon:
    ConnectTimeout: 250 # Ribbon的连接超时时间
    ReadTimeout: 3000 # Ribbon的数据读取超时时间
    OkToRetryOnAllOperations: true # 是否对所有操作都进行重试
    MaxAutoRetriesNextServer: 1 # 切换实例的重试次数
    MaxAutoRetries: 1 # 对当前实例的重试次数

feign:
  hystrix:
    enabled: true # 开启Feign的熔断功能,默认为关闭
    

Feign实现远程调用

ly-user这个模块调用ly-item

  1. 在ly-user的pom.xml文件加入feign的依赖

  2. 在ly-user的LyApplication 启动类上加入**@EnableFeignClients**注解

  3. 在client客户端下面创建一个itemClient接口

  4. @RequestMapping("brand")
    

加上这个前端要用的请求的路径。

  1. 加入Service这个接口中的定义的相关的方法。
  2. 前面加上**@FeignClient(name=“item-service”)** (item-service是这个ly-item这个模块里面的spring.application.name=item-service)
  3. 由于还没有进行优化,我们可以先把pojo类全部复制粘贴过来
  4. 建立一个BrandController进行前端的测试输入这个测试类的请求就好

itemClient:

package com.yunhe.client;

import com.yunhe.pojo.Brand;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//注意:类上面不要写@RequestMapping
@FeignClient(name = "item-service",fallback = ItemClientFallback.class)
public interface ItemClient {

    @GetMapping("brand")
    public List<Brand> listAll();


}
@RestController
public class UserController {

    @Autowired
    private ItemClient itemClient;

    @GetMapping
    public List<Brand> queryAllBrands(){
        return itemClient.listAll();
    }
}

Ribbon负载均衡

  1. 可以知道feignEureka,zuul中已经自带了ribbon和Hystrix,所以不用引入依赖.

Hystrix熔断器

feign里面自带熔断器,但是默认是关闭状态的,需要手动开启

使ly-user模块调用ly-item模块,需要feign和hystrix,进行hystrix步骤:

  1. yml文件加上:
feign:
	hystrix:
	enabled: true #开启熔断器
  1. 创建client包然后进行创建下面的类: //注意:类上面不要写@RequestMapping ,这里的@GetMapping(“brand”)和ly-item里面的controller测试的请求一样。
package com.yunhe.client;

import com.yunhe.pojo.Brand;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//注意:类上面不要写@RequestMapping
@FeignClient(name = "item-service",fallback = ItemClientFallback.class)
public interface ItemClient {
    
    

    @GetMapping("brand")
    public List<Brand> listAll();


}

  1. 创建 ItemClientFallback实现类: ly-item的服务断了不会影响ItemClientFallback方法的执行
package com.yunhe.client;

import com.yunhe.client.ItemClient;
import com.yunhe.pojo.Brand;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Component
public class ItemClientFallback implements ItemClient {
    
    
    @Override
    @GetMapping("brand")
    public List<Brand> listAll() {
    
    
        System.out.println("服务断了,呜呜呜呜。。。");
        return null;
    }
}

zuul网关

  1. 创建一个单独的模块ly-api-gateway,所有的端口号会经过zuul处理。
  2. 当然其他的所有模块都是注册中心的客户端,需要加上**@EnableDiscoveryClient,在主配置文件上面**
  3. **引入网关的依赖,**也需要引入eureka客户端的依赖
<!--zuul网关-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>


        <!--eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  1. 启动类上面 加上**@EnableZuulProxy** 网关代理注解

  2. 在ly-api-gateway的application.yml文件中配置网关,注意一下:routes 下面的 item-service是配置文件中的spring.application.name 的名字

zuul:
	prefix: /api #添加路由前缀
	retryable: true
	routes:
		item-service: /item/** #商品服务
		user-service: /user/** #用户微服务
		cart-service: /cart/** #购物车服务
  1. 网关的所有的配置文件信息
server:
  port: 10000

spring:
  application:
    name: api-gateway

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka
  instance:
    lease-renewal-interval-in-seconds: 5 #每隔6秒发送一次心跳
    lease-expiration-duration-in-seconds: 10 #10秒不发送就过期
    prefer-ip-address: true
    ip-address: 127.0.0.1
    instance-id: ${
    
    spring.application.name}:${
    
    server.port}
zuul:
  prefix: /api # 添加路由前缀
  retryable: true #当网关没有连接上来的时候是否可以重试
  routes:
    item-service: /item/**  #商品微服务 /item下的所有的请求
    user-service: /user/**  #用户微服务
    cart-service: /cart/** #购物车微服务

ribbon:
  ConnectTimeout: 60000 # 连接超时时间(ms)
  ReadTimeout: 60000 # 通信超时时间(ms)
  OkToRetryOnAllOperations: true # 是否对所有操作重试
  MaxAutoRetriesNextServer: 1 # 同一服务不同实例的重试次数
  MaxAutoRetries: 1 # 同一实例的重试次数
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMillisecond: 10000 # 熔断超时时长:10000ms
  1. 通过网关进行访问ly-item里面的增删改查的操作。

    http://localhost:10000/api/item/brand 和 不用网关访问的效果一样 http://localhost:10010/brand

  2. zuul自带hystrix和Ribbon功能,需要我们通过配置文件开启

  3. 网关可以进行过滤的配置

package com.yunhe.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
//注意一下需要加上这个@Component组件 
@Component
public class LoginFilter extends ZuulFilter{
    
    
    /**
     * - pre:请求在被路由之前执行
     * - routing:在路由请求时调用
     * - post:在routing和errror过滤器之后调用
     * - error:处理请求时发生错误调用
     * @return
     */
    @Override
    public String filterType() {
    
    
        return "pre";
    }

    //数字越小优先级越高
    @Override
    public int filterOrder() {
    
    
        return 1;
    }

    //是否进行过滤  true 过滤  false 不进行过滤
    @Override
    public boolean shouldFilter() {
    
    
        return true;
    }

    //run()   过滤的方法
    @Override
    public Object run() throws ZuulException {
    
    
        System.out.println("zuul filter执行了。。。。。");
        return null;
    }
}

猜你喜欢

转载自blog.csdn.net/houzhicongone/article/details/120619304