1.ribbon方法调用

在pom.xml文件中加入
<dependency>
    <groupId>org.springframework.cloud</groupId\>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

注入RestTemplate

@Configuration
public class RestTemplateConfig {
    @Bean
    @LoadBalanced
    //必须加入该注解,否则的话使用rabbon + restTemplate调用服务接口,
    // url会当做普通的url,一般会报类似springcloud java.net.UnknownHostException: COMMONINTEGRATION的错误
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

通过restTemplate调用别的服务接口

@Service
public class UserMessageService {

    @Autowired
    private RestTemplate restTemplate;

    public boolean sentMessage(String phoneNumber, String content) {
        String url = "http://CommonIntegration/mail/send?phoneNumber=" + phoneNumber + "&content=" +content;
        //CommonIntegration为调用的服务名
        Boolean result = restTemplate.getForObject(url, Boolean.class);
        return result;
    }
}

ribbon+restTemplate调用方式实现了负载均衡功能

2.feign方法调用

feign调用方式集成了ribbon,默认实现了负载均衡。

增加依赖

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

开启feign client

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients   //开启注解 EnableFeignClients
public class UserServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class);
    }
}

写具体调用接口

@FeignClient("CommonIntegration") //CommonIntegration代表要调用接口所在的服务名称,
public interface MessageServiceFeign { //定义为接口类型
    @GetMapping("/mail/send") //请求url 及请求方式
    boolean sentMessage(@RequestParam("phoneNumber") String phoneNumber, @RequestParam("content") String content);  //参数说明
}

如下为CommonIntegration服务的/mail/send接口,对比发现两者区别不大,调用方使用了@FeignCleint()注解指定服务名称

@RestController
@RequestMapping("/mail")
public class MailController {

    @Autowired
    private IMailService mailService;

    @GetMapping("/send")
    public boolean sendMail(@RequestParam("phoneNumber") String phoneNumber,@RequestParam("content") String content){
        return mailService.sendMain(phoneNumber,content);
    }
}

如何使用定义的接口


@Autowired
private MessageServiceFeign messageServiceFeign; //编译器会报错,在运行时候才能指定具体对象

public boolean sentMessageByFeign(String phoneNumber,String content){
    boolean result = messageServiceFeign.sentMessage(phoneNumber, content);
    return result;
}
03-05 22:29