我是靠谱客的博主 落寞鸵鸟,最近开发中收集的这篇文章主要介绍SpringCloud总结--SpringCloud简单使用以及Ribbon和Feign的使用,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

SpringCloud是基于SpringBoot的一整套实现微服务的框架。他提供了微服务开发所需的配置管理、服务发现、断路器、智能路由、微代理、控制总线、全局锁、决策竞选、分布式会话和集群状态管理等组件。最重要的是,跟spring boot框架一起使用的话,会让你开发微服务架构的云服务非常好的方便。SpringCloud也是基于RPC远程调用协议,所以也是需要一个注册中心,注册中心可以使用Eureka,zk(Zookeeper)等。

SpringCloud特点:

   1、SpringCloud 是基于SpringBoot的,所以拥有SpringBoot的所以特点
   2.约定优于配置
   3、开箱即用、快速启用
   4、适用于各种环境
   5、轻量级的组件
   6、组件否支持很丰富,功能很齐全
   7、选型中立

下面就对SpringCloud的使用以及结合Ribbon的使用(注册中心使用Eureka)

 

一、注册中心Eureka的使用(这边加入了Eureka的认证)

   a、pom.xml依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.zhuojing</groupId>
  <artifactId>springCloud-eureka-demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.2.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka-server</artifactId>
			<version>1.3.5.RELEASE</version>
		</dependency>
		
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		
  </dependencies>
 <build>
    
    <plugins>
      <plugin>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-maven-plugin</artifactId>
	  </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
 </build>
</project>

    b、application.yml

security:
  user:
    password: zj123
    name: user
  basic:
    enabled: true
server:
  port: 8761
eureka:
  client: 
    register-with-eureka: false
    fetch-registry: false
    defaultZone: http://user:zj123@localhost:8761/eureka

      eureka.client.register-with-eureka=false    ##当前Eureke只做服务,不作为客户端,因为在高可用的环境下Eureka是服务也是客户端,用于Eureka的同步
      eureka.client.fetch-registry=false          ##当前Eureke只做服务,不作为客户端,因为在高可用的环境下Eureka是服务也是客户端,用于Eureka的同步

c、启动类

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

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

注:启动后访问http://localhost:8761 ,用户名密码:user,zj123(根据security的配置)

二、服务发布者

1.pom.xml依赖(这边添加了Mybaits的依赖)

<parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.2.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
  </parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <mybatis-spring-boot.version>1.2.0</mybatis-spring-boot.version>
    <mysql-connector.version>5.1.39</mysql-connector.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-eureka</artifactId>
		<version>1.3.5.RELEASE</version>
	</dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>${mybatis-spring-boot.version}</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

2、application.yml

server:
  port: 8098
spring:
  application:
    name: provider-user
  datasource:
    url: jdbc:mysql://localhost:3306/spring-cloud
    username: root
    password: zj123456
    driver-class-name: com.mysql.jdbc.Driver
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.zhuojing.bean
eureka:
  client: 
    serviceUrl:
      defaultZone: http://user:zj123@localhost:8761/eureka
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}

3、Controller接口

@RestController
public class UserController {

	@Autowired
	private UserDao userDao;
	@GetMapping("/simple/{id}")
	public User getUserById(@PathVariable Long id){
		return userDao.getById(id);
	}
}

注:这边dao使用Mybaits实现的就详细说明,这边接口就是根据请求参数请求一张表记录

4、启动类

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

@SpringBootApplication
@EnableEurekaClient
public class ApplocationTest {

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

}

三、服务消费者使用(这边使用Ribbon进行调用)

1、pom.xml的依赖

<parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.2.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
  </parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <mybatis-spring-boot.version>1.2.0</mybatis-spring-boot.version>
    <mysql-connector.version>5.1.39</mysql-connector.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-eureka</artifactId>
		<version>1.3.5.RELEASE</version>
	</dependency>
</dependencies>

2、application.yml

server:
  port: 8089
spring:
  application:
    name: customer-user
eureka:
  client: 
    serviceUrl: 
      defaultZone: http://user:zj123@localhost:8761/eureka
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
provider-user: 
  ribbon: 
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

3、调用:使用Ribbon调用

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.zhuojing.bean.User;

@RestController
public class UserController {

	@Autowired
	private RestTemplate restTemplate;

	@GetMapping(value="/simple/{id}",produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
	public User findUserById(@PathVariable Long id){
		//服务提供者地址  microservice-provider-user
		return this.restTemplate.getForObject("http://PROVIDER-USER/simple/"+id, User.class);
	}
	
}

4、启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
public class AppCusRibbonPropertiesTest {

	@Bean
	@LoadBalanced
	public RestTemplate restTemplate(){
		return new RestTemplate();
	}
	public static void main(String[] args) {
		SpringApplication.run(AppCusRibbonPropertiesTest.class, args);
	}
}

使用Ribbon即时使用注解@LoadBalanced  使用即可

同时这边使用基于配置文件的方式配置了Ribbon的调用服务的负载策略:

provider-user: 
  ribbon: 
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

这边使用的是随机的方式,Ribbon还提供了多做负载均衡策略如轮询,选择最小并发等,同时还可以自定义负载均衡策略,这边就不详细介绍,刚兴趣的可以自行查阅下资料

四、消费者的使用(使用Feign)

Feign是一个客户端负载均衡的组件,默认负载均衡策略是轮询

1、pom.xml 依赖

<parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.2.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
  </parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <mybatis-spring-boot.version>1.2.0</mybatis-spring-boot.version>
    <mysql-connector.version>5.1.39</mysql-connector.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-eureka</artifactId>
		<version>1.3.5.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-feign</artifactId>
		<version>1.3.5.RELEASE</version>
	</dependency>
</dependencies>

2、application.yml

server:
  port: 8089
spring:
  application:
    name: customer-user
eureka:
  client: 
    serviceUrl: 
      defaultZone: http://user:zj123@localhost:8761/eureka
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}

3、编写feign接口,使用@FeignClient注解

import org.springframework.cloud.netflix.feign.FeignClient;

import com.config.Configuration1;
import com.zhuojing.bean.User;

import feign.Param;
import feign.RequestLine;

@FeignClient(name="provider-user",configuration=Configuration1.class)
public interface UserFeignClient {
  
	
	@RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)
	public User getUserById(@PathVariable("id") Long id); 
// 两个坑:1. @GetMapping不支持   2. @PathVariable得设置value
}

4、Controller调用类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.zhuojing.bean.User;
import com.zhuojing.feign.UserFeignClient;

@RestController
public class UserController {

	@Autowired
	private UserFeignClient userFeignClient;

	@GetMapping(value="/simple/{id}",produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
	public User findUserById(@PathVariable Long id){
		
		return userFeignClient.getUserById(id);
	}
}

4、启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ApplicationCustomerFeignTest {

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

注:Feign使用是第一次可能会出现请求超时的问题,针对这个问题,有以下几种角色方案

 # 解决第一次请求报超时异常的方案:
  hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000 
# 或者:
  hystrix.command.default.execution.timeout.enabled: false

# 或者:  
  feign.hystrix.enabled: false ## 索性禁用feign的hystrix支持

五、其他说明

服务消费者获取List结果(坑,先转化为数组)
        @GetMapping("/getAllUser")
    public List<User> getAllUser(){
        User[] users = this.restTemplate.getForObject("http://provider-user/getAllUser", User[].class);
        List<User> list = Arrays.asList(users);
        for (User user : list) {
            System.out.println(user.getId());
        }
        return list;
    }

最后

以上就是落寞鸵鸟为你收集整理的SpringCloud总结--SpringCloud简单使用以及Ribbon和Feign的使用的全部内容,希望文章能够帮你解决SpringCloud总结--SpringCloud简单使用以及Ribbon和Feign的使用所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(54)

评论列表共有 0 条评论

立即
投稿
返回
顶部