首先不能随意导入依赖,因为在openapi-gateway部分里面导入了openapi-cache的依赖以致于我在openapi-gateway里面使用CacheService被认为需要再次使用openapi-cache模块里通过gitee才能连接redis。

        其次,在CacheService添加下面的注释之后要编写相应的Fallback文件

@FeignClient(value ="OPENAPI-CACHE" ,fallback = CacheServiceFallback.class)

         CacheServiceFallback代码如下:

package com.zgz.openplatform.gateway.feign;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;


/**
 * feign的降级机制,具体实现要一个一个填写
 */
@Component
public class CacheServiceFallback   implements CacheService{

    //日志在logback-spring.xml里面写好了,这里调用一下
    private static Logger logger = LoggerFactory.getLogger(CacheServiceFallback.class);

    /**
     * 保存数据到缓存中的降级方法
     * @param key
     * @param value
     * @param expireTime
     * @return
     * @throws Exception
     */
    public boolean save2Redis( String key, String value, long expireTime) throws Exception {
        logger.error("save2Redis出现异常进行降级,{},{}",key,value);         //打印出日志里面记录的异常
        return false;
    }


    public String getFromRedis( String key) throws Exception {
        logger.error("getFromRedis出现异常进行降级,{}",key);
        return null;
    }


    public boolean deleteKey( String key) throws Exception {
        logger.error("save2Redis出现异常进行降级,{}",key);         //打印出日志里面记录的异常
        return false;
    }


    public boolean expire( String key,  long expireTime) throws Exception {
        logger.error("save2Redis出现异常进行降级,{}",key);         //打印出日志里面记录的异常
        return false;
    }

    public Long getAutoIncrementId( String key) throws Exception {
        logger.error("getautoincrementidFallBack出现异常进行降级,{}",key);         //打印出日志里面记录的异常
        return null;
    }

    public Set<Object> sMembers( String key) throws Exception {
        logger.error("smembersFallBack出现异常进行降级,{}",key);         //打印出日志里面记录的异常
        return null;
    }


    public Long sAdd( String key,  String member) throws Exception {
        logger.error("saddFallBack出现异常进行降级,{},{}",key,member);         //打印出日志里面记录的异常
        return null;
    }


    public Long sAdd(String key, String[] members) throws Exception {
        logger.error("saddsFallBack出现异常进行降级,{},{}",key,members);         //打印出日志里面记录的异常
        return null;
    }


    public Long sRemove( String key,  String member) throws Exception {
        logger.error("sremoveFallBack出现异常进行降级,{},{}",key,member);         //打印出日志里面记录的异常
        return null;
    }


    public boolean hSet( String key,  String field,  String value) throws Exception {
        logger.error("hsetFallBack出现异常进行降级,{},{},{}",key,field,value);         //打印出日志里面记录的异常
        return false;
    }

    public String hGet( String key,  String field) throws Exception {
        logger.error("hgetFallBack出现异常进行降级,{},{}",key,field);         //打印出日志里面记录的异常
        return null;
    }


    public Map<Object, Object> hGetAll( String key) throws Exception {
        logger.error("hgetallFallBack出现异常进行降级,{}",key);         //打印出日志里面记录的异常
        return null;
    }


    public boolean hMSet( String key, Map<Object, Object> values) throws Exception {
        logger.error("hmsetFallBack出现异常进行降级,{},{}",key,values);         //打印出日志里面记录的异常
        return false;
    }


    public Set<String> findKeyByPartten( String partten) throws Exception {
        logger.error("findkeybyparttenFallBack出现异常进行降级,{}",partten);         //打印出日志里面记录的异常
        return null;
    }


    public Long getAutoIncrementId( String key,  long delta) throws Exception {
        logger.error("getautoincrementIdFallBack出现异常进行降级,{},{}",key,delta);         //打印出日志里面记录的异常
        return null;
    }

    public Long hIncrementId( String key,  String field,  long delta) throws Exception {
        logger.error("hincrementidFallBack出现异常进行降级,{},{},{}",key,field,delta);         //打印出日志里面记录的异常
        return null;
    }


    public boolean setNx( String key,  String value,  long expireTime) throws Exception {
        logger.error("setnxFallBack出现异常进行降级,{},{},{}",key,value,expireTime);         //打印出日志里面记录的异常
        return false;
    }

    public boolean hMSet( String key, Object values) throws Exception {
        logger.error("hmsetFallBack出现异常进行降级,{},{}",key,values);         //打印出日志里面记录的异常
        return false;
    }




}

最后,对于在模块里面添加缓存机制的逻辑是

        1、编写pom文件,添加相应的依赖

  <dependencies>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</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-openfeign</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!--cache-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>


        <dependency>
            <groupId>com.qianfeng</groupId>
            <artifactId>openapi-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>


    </dependencies>

        2、编写application.yml文件,开启降级以及hystrix的相关配置

server:
  port: 31100
spring:
  application:
    name: openapi-gateway
eureka:
  client:
    service-url:
      defaultZone: http://localhost:20000/eureka    #我们的注册中心的zone地址
  instance:
    prefer-ip-address: true
management:
  endpoints:
    web:
      exposure:
        include: '*'   #所有的监控管理地址
zuul:
  ignored-service: '*'     #拦截所有的服务,不带代理列表中显示,那么不能发起请求,需要手动添加服务
  routes:
    openapi-cache: '/*'    #配置所有的服务都转发到openapi-cache缓存服务中,目的是使得我们的zuul可以使用,但是实际开发中我们不会将请求转存到缓存,可以写一个没有任何功能的测试服务来进行代理

feign:
  hystrix:
    enabled: true     #开启降级
ribbon:
  ConnectTimeOut: 2000
  ReadTimeOut: 5000
hystrix:
  shareSecurityContext: true  #上下文分享
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 5000


        3、编写CacheService

package com.zgz.openplatform.gateway.feign;


import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

/**
 * 这个是我们用于方位缓存微服务的feign客户端,这里面主要写的都是我们想要访问的缓存的对应的地址以及参数
 */
@FeignClient(value ="OPENAPI-CACHE" ,fallback = CacheServiceFallback.class)
public interface CacheService {

    @PostMapping("/cache/set/{key}/{value}/{expireTime}")
    boolean save2Redis(@PathVariable String key, @PathVariable String value, @PathVariable long expireTime) throws Exception ;

    @GetMapping("/cache/get/{key}")

    String getFromRedis(@PathVariable String key) throws Exception;

    @PostMapping("/cache/delete/{key}")
    boolean deleteKey(@PathVariable String key) throws Exception ;

    @PostMapping("/cache/expire/{key}/{expireTime}")
    boolean expire(@PathVariable String key, @PathVariable long expireTime) throws Exception;

    @GetMapping("/cache/getid/{key}")
    Long getAutoIncrementId(@PathVariable String key) throws Exception;

    @GetMapping("/cache/smembers/{key}")
    Set<Object> sMembers(@PathVariable String key) throws Exception ;

    @PostMapping("/cache/sadd/{key}/{member}")
    Long sAdd(@PathVariable String key, @PathVariable String member) throws Exception ;

    @PostMapping("/cache/sadds/{key}")
    Long sAdd(@PathVariable String key, @RequestParam("members") String[] members) throws Exception;

    @PostMapping("/cache/sremove/{key}/{member}")
    Long sRemove(@PathVariable String key, @PathVariable String member) throws Exception ;


    @PostMapping("/cache/hset/{key}/{field}/{value}")
    boolean hSet(@PathVariable String key, @PathVariable String field, @PathVariable String value) throws Exception ;

    @GetMapping("/cache/hget/{key}/{field}")
    String hGet(@PathVariable String key, @PathVariable String field) throws Exception;


    @GetMapping("/cache/hgetall/{key}")
    Map<Object, Object> hGetAll(@PathVariable String key) throws Exception;

    @PostMapping("/cache/hmset/{key}")
    boolean hMSet(@PathVariable String key, @RequestBody Map<Object, Object> values) throws Exception ;


    @GetMapping("/cache/keys/{partten}")
    Set<String> findKeyByPartten(@PathVariable String partten) throws Exception ;

    @GetMapping("/cache/increment/{key}/{delta}")
    Long getAutoIncrementId(@PathVariable String key, @PathVariable long delta) throws Exception;

    @GetMapping("/cache/hIncrementid/{key}/{field}/{delta}")
    Long hIncrementId(@PathVariable String key, @PathVariable String field, @PathVariable long delta) throws Exception;

    @PostMapping("/cache/setnx/{key}/{value}/{expireTime}")
    boolean setNx(@PathVariable String key, @PathVariable String value, @PathVariable long expireTime) throws Exception;

    /**
     * 这个方法和上面的hMSet是一样的作用,都是将参数转成json写出去
     * @param key
     * @param value
     * @return
     * @throws Exception
     */
    @PostMapping("/cache/hmset/{key}")
    boolean hMSet(@PathVariable String key, @RequestBody Object value) throws Exception ;


}

        4、编写相应的fallback文件

package com.zgz.openplatform.gateway.feign;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;


/**
 * feign的降级机制,具体实现要一个一个填写
 */
@Component
public class CacheServiceFallback  implements CacheService{

    //日志在logback-spring.xml里面写好了,这里调用一下
    private static Logger logger = LoggerFactory.getLogger(CacheServiceFallback.class);

    /**
     * 保存数据到缓存中的降级方法
     * @param key
     * @param value
     * @param expireTime
     * @return
     * @throws Exception
     */
    public boolean save2Redis( String key, String value, long expireTime) throws Exception {
        logger.error("save2Redis出现异常进行降级,{},{}",key,value);         //打印出日志里面记录的异常
        return false;
    }


    public String getFromRedis( String key) throws Exception {
        logger.error("getFromRedis出现异常进行降级,{}",key);
        return null;
    }


    public boolean deleteKey( String key) throws Exception {
        logger.error("save2Redis出现异常进行降级,{}",key);         //打印出日志里面记录的异常
        return false;
    }


    public boolean expire( String key,  long expireTime) throws Exception {
        logger.error("save2Redis出现异常进行降级,{}",key);         //打印出日志里面记录的异常
        return false;
    }

    public Long getAutoIncrementId( String key) throws Exception {
        logger.error("getautoincrementidFallBack出现异常进行降级,{}",key);         //打印出日志里面记录的异常
        return null;
    }

    public Set<Object> sMembers( String key) throws Exception {
        logger.error("smembersFallBack出现异常进行降级,{}",key);         //打印出日志里面记录的异常
        return null;
    }


    public Long sAdd( String key,  String member) throws Exception {
        logger.error("saddFallBack出现异常进行降级,{},{}",key,member);         //打印出日志里面记录的异常
        return null;
    }


    public Long sAdd(String key, String[] members) throws Exception {
        logger.error("saddsFallBack出现异常进行降级,{},{}",key,members);         //打印出日志里面记录的异常
        return null;
    }


    public Long sRemove( String key,  String member) throws Exception {
        logger.error("sremoveFallBack出现异常进行降级,{},{}",key,member);         //打印出日志里面记录的异常
        return null;
    }


    public boolean hSet( String key,  String field,  String value) throws Exception {
        logger.error("hsetFallBack出现异常进行降级,{},{},{}",key,field,value);         //打印出日志里面记录的异常
        return false;
    }

    public String hGet( String key,  String field) throws Exception {
        logger.error("hgetFallBack出现异常进行降级,{},{}",key,field);         //打印出日志里面记录的异常
        return null;
    }


    public Map<Object, Object> hGetAll( String key) throws Exception {
        logger.error("hgetallFallBack出现异常进行降级,{}",key);         //打印出日志里面记录的异常
        return null;
    }


    public boolean hMSet( String key, Map<Object, Object> values) throws Exception {
        logger.error("hmsetFallBack出现异常进行降级,{},{}",key,values);         //打印出日志里面记录的异常
        return false;
    }


    public Set<String> findKeyByPartten( String partten) throws Exception {
        logger.error("findkeybyparttenFallBack出现异常进行降级,{}",partten);         //打印出日志里面记录的异常
        return null;
    }


    public Long getAutoIncrementId( String key,  long delta) throws Exception {
        logger.error("getautoincrementIdFallBack出现异常进行降级,{},{}",key,delta);         //打印出日志里面记录的异常
        return null;
    }

    public Long hIncrementId( String key,  String field,  long delta) throws Exception {
        logger.error("hincrementidFallBack出现异常进行降级,{},{},{}",key,field,delta);         //打印出日志里面记录的异常
        return null;
    }


    public boolean setNx( String key,  String value,  long expireTime) throws Exception {
        logger.error("setnxFallBack出现异常进行降级,{},{},{}",key,value,expireTime);         //打印出日志里面记录的异常
        return false;
    }

    public boolean hMSet( String key, Object values) throws Exception {
        logger.error("hmsetFallBack出现异常进行降级,{},{}",key,values);         //打印出日志里面记录的异常
        return false;
    }




}

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐