The simplified construction process of springcloud + Eureka + feign + ribbon includes fuse, gateway and redis cache [2]

Simplified construction process and crud exercise of springcloud + Eureka + feign + ribbon [1]

Modification and expansion of

1. Modify centerfeign Java, set all the return values to string

/**
 * 是consumer调用provider(需要指定provider的名字)
 * 请求的清单列表:规定调用地址、参数、返回值
 * 在正常走通的时候不走CenterFeignFallBack,当provider down的时候走熔断器,相当于是类的try-catch
 */
@FeignClient(name = "provider",fallback = CenterFeignFallBack.class)
public interface CenterFeign {
    @GetMapping("/optionData.do")
    public String optionData();

    @PostMapping("/showEmpData.do")
    //Feign:不支持对象传参,所以要用@RequestBody
    public String showEmpData(@RequestBody Emp emp);

    @PostMapping("/add.do")
    public String add(@RequestBody Emp emp);

    @PostMapping("/edit.do")
    public String edit(@RequestBody  Emp emp);

    @GetMapping("/del.do")
    public String del(@RequestParam("empno") Integer empno);
}

2. At centerfeign Under the same package of Java, create a centerfeignfallback. Net that implements the centerfeign interface Java as fuse

@Component
public class CenterFeignFallBack implements CenterFeign {
    @Override
    public String optionData() {
        return "provider-optionData-error";
    }

    @Override
    public String showEmpData(Emp emp) {
        return "provider-showEmpData-error";
    }

    @Override
    public String add(Emp emp) {
        return "provider-add-error";
    }

    @Override
    public String edit(Emp emp) {
        return "provider-edit-error";
    }

    @Override
    public String del(Integer empno) {
        return "provider-del-error";
    }
}

3. Modify the centercontroller of the consumer Java, all return values are changed to string

@RestController
public class CenterController{
    @Resource
    private CenterFeign centerFeign;

    @GetMapping("/optionData-consumer.do")
    public String optionData() {
        return centerFeign.optionData();
    }

    @PostMapping("/showEmpData-consumer.do")
    public String showEmpData(@RequestBody Emp emp) {
        return centerFeign.showEmpData(emp);
    }

    @PostMapping("/add-consumer.do")
    public String add(@RequestBody Emp emp) {
        return centerFeign.add(emp);
    }

    @PostMapping("/edit-consumer.do")
    public String edit(@RequestBody Emp emp) {
        return centerFeign.edit(emp);
    }

    @GetMapping("/del-consumer.do")
    public String del(@RequestParam("empno") Integer empno) {
        return centerFeign.del(empno);
    }
}

4. Confirm the configuration file application in the consumer Whether the fuse feign is turned on in the properties hystrix. Enabled = true, if not, add

#端口号
server.port=8764
#应用名
spring.application.name=consumer
#eureka客户端服务url默认区域
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
#开启熔断器
feign.hystrix.enabled=true
#下线名称.ribbon.NF加载平衡规则类名,这里先注释
provider.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule

5. Start service test

visit http://localhost:8761/

Found all services registered

There is no problem walking the provider normally

It's OK to go to the consumer, but the returned format is string type, not JSON type, but it doesn't matter. The format is still JSON format. It doesn't matter how the foreground turns

@H_ 301_ 100@

How do I get there?

Now stop a provider manually

Because I have opened the load balancing policy here (provider. Ribbon. Nfloadbalancerruleclassname = com. Netflix. Loadbalancer. Randomrule in the configuration file in the consumer), there is a certain chance to trigger the fuse,

This is equivalent to a try catch between classes. If there is no fuse, the error code will be reported 100% Here, I'll turn off load balancing first and test whether fault tolerance is gone (guess, will it go?)

I've tested it so many times here, but I didn't go, so obviously I didn't go. Why?

Because if the load balancing policy is not set manually, polling is used by default Mechanism, what is ribbon polling mechanism?

Simply put, there are three ABC servers. Under normal circumstances, go to a - > b - > C. when one goes down, it will skip automatically. For example, if B goes down, it is a - > C

I personally understand the above. Please correct me if there is any error. I am willing to ~

Now, since there is no problem with one server, why don't I stop both providers?

The answer is yes, cliff walk~~

6. There is no problem after the test. Now add the gateway function module

New module (spring initializr) zuul client

7. Edit the configuration file application properties

#网关端口
server.port=8765
#应用名
spring.application.name=zuul
#网关路径提供者,后面的**表示:xxx.do
zuul.routes.provider=/pro/**/
#网关路径消费者,后面的**表示:xxx.do
zuul.routes.consumer=/con/**/
#网关走熔断机制
#ribbon超时设置
ribbon.ReadTimeout=30000
ribbon.ConnectTimeout=30000

8. Add comments on the startup class

//开启网关代理
@EnableZuulProxy
//开启eureka客户端
@EnableEurekaClient
@SpringBootApplication
public class ZuulClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(ZuulClientApplication.class,args);
    }

}

9. Start service test

Test provider

Test consumer

10. Role of gateway

After unifying the IP addresses and port numbers of all clients, we just need to alias applications at different levels (that's right here)

11. Add redis cache

11.1 add redis dependency in POM file of provider one module

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

11.2 modify the deptserviceimpl file of the provider one module and add @ Autowired private redistemplate redistemplate;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private Redistemplate redistemplate;

    @Override
    public Map<String,Object> optionData() {
        Map<String,Object> map=new HashMap<>();
        List<Map<String,Object>> list = deptMapper.selAllDeptData();
        // 定义Redis存储集合的对象
        ListOperations<String,Map<String,Object>> redisList = redistemplate.opsForList();
        //拼接Redis中存储数据对应的key
        String key = "depts";
        //判断Redis中是否有key,没有就说明是第一次访问,将数据放入Redis
        if(!redistemplate.hasKey(key)){
            //直接将数据库查询出来的值放入Redis
            System.out.println("provider-one-optionData的值已经放入Redis");
            redisList.leftPushAll(key,list);
        }
        map.put("data",list);
        return map;
    }
}

11.3 modify the corresponding deptservice, and the return value becomes map

public interface DeptService {
    Map<String,Object> optionData();
}

11.4 modify the centercontroller and change the return value type to map

    public Map<String,Object> optionData() {
        return deptService.optionData();
    }

11.5 similarly, in the POM of provider two Add redis dependency to XML

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

11.6 modify the deptserviceimpl file of the provider two module and put the data into redis if (! Redistemplate. Haskey (key)) {/ / directly put the value queried in the database into redis system.out.println ("the value of the provider two optiondata has been put into redis"); redislist.leftpushall (key, list); return map;}}

11.7 modify the corresponding deptservice, Object > optiondata();}

11.8 modify centercontroller, Object > optiondata() {return deptservice. Optiondata();}

11.9 update the configuration file of provider one module application Properties, add redis configuration

#服务端口号
server.port=8762
#应用名
spring.application.name=provider
#eureka客户端服务url默认区域
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

#数据源驱动类名
spring.datasource.driver-class-name=com.MysqL.jdbc.Driver
#数据源url
spring.datasource.url=jdbc:MysqL:///kh75
#数据源用户名
spring.datasource.username=root
#数据源密码
spring.datasource.password=admin



#后期会写mapper.xml,这里先注释
#mybatis.mapper-locations=classpath:mapper/*.xml

#给实体类起别名,同样这里先注释
#mybatis.type-aliases-package=cn.kgc.vo

#配置Redis
spring.redis.port=6379
#redis所在的主机地址
spring.redis.host=xxx.xxx.xxx
spring.redis.database=0

11.10 update the configuration file of the provider two module application Properties, add redis configuration

#服务端口号
server.port=8763
#应用名
spring.application.name=provider
#eureka客户端服务url默认区域
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

#数据源驱动类名
spring.datasource.driver-class-name=com.MysqL.jdbc.Driver
#数据源url
spring.datasource.url=jdbc:MysqL:///kh75
#数据源用户名
spring.datasource.username=root
#数据源密码
spring.datasource.password=admin



#后期会写mapper.xml,同样这里先注释
#mybatis.type-aliases-package=cn.kgc.vo
#配置Redis
spring.redis.port=6379
#redis所在的主机地址
spring.redis.host=xxx.xxx.xx
spring.redis.database=0

11.11 update the centerfeign of the consumer, and all return values are map

@FeignClient(name = "provider",fallback = CenterFeignFallBack.class)
public interface CenterFeign {
    @GetMapping("/optionData.do")
     Map<String,Object> optionData();

    @PostMapping("/showEmpData.do")
    //Feign:不支持对象传参,所以要用@RequestBody
    Map<String,Object> showEmpData(@RequestBody Emp emp);

    @PostMapping("/add.do")
    Map<String,Object> add(@RequestBody Emp emp);

    @PostMapping("/edit.do")
    Map<String,Object> edit(@RequestBody  Emp emp);

    @GetMapping("/del.do")
    Map<String,Object> del(@RequestParam("empno") Integer empno);
}

11.12 update centerfeignfallback

@Component
public class CenterFeignFallBack implements CenterFeign {
    private Map<String,Object> map = new HashMap<> ();
    @Autowired
    private Redistemplate redistemplate;
    @Override
    public Map<String,Object> optionData() {
         ListOperations<String,Object>> redisList = redistemplate.opsForList();
        map.put("msg","provider-optionData-error");
        map.put("feign-data",redisList.range("depts",-1));
        return map;
    }

    @Override
    public Map<String,Object> showEmpData(Emp emp) {
         ListOperations<String,"provider-showEmpData-error");
        //这里对应的serviceImp里面还没修改成Redis,先放着
        map.put("feign-data",redisList.range("emps",Object> add(Emp emp) {
        map.put("msg","provider-add-error");
        return map;
    }

    @Override
    public Map<String,Object> edit(Emp emp) {
        map.put("msg","provider-edit-error");
        return map;
    }

    @Override
    public Map<String,Object> del(Integer empno) {
        map.put("msg","provider-del-error");
        return map;
    }
}

11.13 modify the centercontroller in the consumer and change the return value to map

@RestController
public class CenterController{
    @Resource
    private CenterFeign centerFeign;

    @GetMapping("/optionData-consumer.do")
    public Map<String,Object> optionData() {
        return centerFeign.optionData();
    }

    @PostMapping("/showEmpData-consumer.do")
    public Map<String,Object> showEmpData(@RequestBody Emp emp) {
        return centerFeign.showEmpData(emp);
    }

    @PostMapping("/add-consumer.do")
    public Map<String,Object> add(@RequestBody Emp emp) {
        return centerFeign.add(emp);
    }

    @PostMapping("/edit-consumer.do")
    public Map<String,Object> edit(@RequestBody Emp emp) {
        return centerFeign.edit(emp);
    }

    @GetMapping("/del-consumer.do")
    public Map<String,Object> del(@RequestParam("empno") Integer empno) {
        return centerFeign.del(empno);
    }
}

11.14 check whether redis dependency is added in the POM file of the consumer, but not

11.15 open all modules for testing

Disconnect the provider, and in theory, connect the fuse and redis data

above....

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>