Ruoyi microservice Spring Cloud version—implementing service invocation and load balancing based on nacos+Feign

Table of contents

A general microservice calling code is as follows, there are several problems

Two solutions – service governance

Introduction and use of three nacos

4. Use Feign to achieve load balancing

5. Ruoyi Platform—Call other microservices based on Feign


A general microservice calling code is as follows, there are several problems

Product product=restTemplate.getForObject("http://localhost:8081/product/"+pid,Product.calss)

1. Once the address information provided by the service changes, we are not allowed to modify the Java code of the service caller

2. Once the provider is clustered, the service caller cannot achieve load balancing.

3. Once the number of microservices becomes more and more, how to manage this service list becomes a problem.

Two solutions – service governance

The service registration center is required to dynamically implement service governance. Service governance is the core module of microservices and is used to realize automatic registration and discovery of each microservice.

Commonly used registration centers

1. Zookeeper: It is a distributed service framework and a sub-project of Apache Hadoop. It is mainly used to solve some data management problems often encountered in distributed applications: unified naming service, status synchronization service, cluster management, distribution Management of application configuration items, etc.

2. Eureka: It is an important component in Springcloud Netflix. Its main function is service registration and discovery. But it is now closed source.

3. Consul: An open source tool developed based on Go language. It mainly provides service registration, service discovery and configuration management functions for distributed and service-oriented systems. Consul’s functions are very practical, including: service registration/discovery, health check, Features such as key/value storage, multi-data centers and distributed consistency guarantees. Consul itself is just a binary executable file, so installation and deployment are very simple. You only need to download it from the official website and execute the corresponding startup script.

4.Nacos: nacos is a dynamic service discovery, configuration management and service management platform that makes it easier to construct cloud native references. It is one of the components of SprinCloud Alibaba and is responsible for service registration discovery and service configuration. It can be considered that nacos=eureka+config

Introduction and use of three nacos

nacos is dedicated to discovering, configuring and managing microservices. It functions as a registration center to manage each registered microservice.

nacos uses:

1. Add dependencies

<dependency>
	<groupId>com.alibaba.cloud</groupId>
	<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

2. The nacos service address in the application.yml file

# Spring
spring: 
  application:
    # Application Name
    name: ruoyi-xxxx 
  cloud:
    nacos:
      discovery:
        # Service registration address
        server-addr: 127.0.0.1:8848

3. inApplicationAdd annotations to the startup class@EnableDiscoveryClient

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

4. Start the nacos service and viewNacosConsole service list

5. Code verification, obtain the address of the microservice from nacos, the code is modified as follows

List<ServiceInstance> instanches=discoveryClient.getInstance("service-product");
SeriviceInstance instance=instance.get(0);
Product product=restTemplate.getForObject("http://"+instance.getHost()+":"
+instance.getPost()+"/product/"+pid,Proudct.class);

Code problem: SeriviceInstance instance=instance.get(0): only the first one can be obtained, load balancing cannot be achieved

4. Use Feign to achieve load balancing

Feign is a declarative pseudo-http client provided by Spring Cloud. It makes calling remote services as easy as calling local services. Just create an excuse and add an annotation.

As a registration center, Nacos is very compatible with Feign. Feign is integrated into Ribbon by default, so using Feign under Nacos achieves load balancing by default.

5. Ruoyi Platform—Call other microservices based on Feign

Specific steps are as follows:

(1). Create an API to obtain user information in the system module

code show as below:

/**
     * Get user information
     */
    @GetMapping("/getUserByUsername/{username}")
    public SysUser getUserByUsername(@PathVariable("username") String username)
    {
         SysUser sysUser = userService.selectUserByUserName(username);
         return sysUser;
    }

(2) Create the UserService file in the ruoyi-whaletest module and use Feign to call the remote user microservice

 

Add the code of the new UserSerice.java file as follows, add
@FeignClient(value=”ruoyi-system”), where ruoyi-system is the service name of nacos

Code:

package com.ruoyi.whaletest.remote;


import com.ruoyi.system.api.domain.SysUser;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;



@FeignClient(value="ruoyi-system")
public interface UserService {

    @GetMapping("/user/getUserByUsername/{username}")
    SysUser getUserByUsername(@PathVariable("username") String username);
}

(3) In the previous section of the article “Ruoyi microservice springcloud version – new module to implement addition, deletion, modification and query》The contract Controller performs remote calls and prints

1. Add UserService

 @Autowired
    private UserService userService;

2. Call the getUserByUsername method

 SysUser sysUser= userService.getUserByUsername(“admin”);

@RestController
@RequestMapping("/contract")
public class ContractController extends BaseController
{
    @Autowired
    private IContractService contractService;

    @Autowired
    private UserService userService;
    /**
     * Query contract list
     */
    @PreAuthorize(hasPermi = "contract:contract:list")
    @GetMapping("/list")
    public TableDataInfo list(Contract contract)
    {
        startPage();
        List<Contract> list = contractService.selectContractList(contract);
        SysUser sysUser= userService.getUserByUsername("admin");
        logger.info("============="+sysUser.getNickName());
        return getDataTable(list);
    }
}

3. Run each microservice. Open the contract menu and the execution results are as follows, indicating that the call is successful.

(4) Generally, if you add feign according to the platform, you need to add the following dependencies

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-openfeign</artifactId>
   <version>2.2.0.RELEASE</version>
</dependency>

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*