Spring Boot中的缓存支持(二)使用Redis做集中式缓存

虽然EhCache已经能够适用很多应用场景,但是由于EhCache是进程内的缓存框架,在集群模式下时,各应用服务器之间的缓存都是独立的,因此在不同服务器的进程间会存在缓存不一致的情况。即使EhCache提供了集群环境下的缓存同步策略,但是同步依然需要一定的时间,短暂的缓存不一致依然存在。

在一些要求高一致性(任何数据变化都能及时的被查询到)的系统和应用中,就不能再使用EhCache来解决了,这个时候使用集中式缓存是个不错的选择,因此本文将介绍如何在Spring Boot的缓存支持中使用Redis进行数据缓存。

下面以上一篇的例子作为基础进行改造,将缓存内容迁移到redis中。

准备工作

可以下载案例Chapter4-4-1,进行下面改造步骤。

先来回顾一下在此案例中,我们做了什么内容:

  • 引入了spring-data-jpaEhCache
  • 定义了User实体,包含idnameage字段
  • 使用spring-data-jpa实现了对User对象的数据访问接口UserRepository
  • 使用Cache相关注解配置了缓存
  • 单元测试,通过连续的查询和更新数据后的查询来验证缓存是否生效

开始改造

  • 删除EhCache的配置文件src/main/resources/ehcache.xml

  • pom.xml中删除EhCache的依赖,增加redis的依赖:

 
    
1
2
3
4
 
    
<dependency>
<groupId>org.springframework.boot </groupId>
<artifactId>spring-boot-starter-redis </artifactId>
</dependency>
  • application.properties中增加redis配置,以本地运行为例,比如:
 
    
1
2
3
4
5
6
 
    
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1

我们需要做的配置到这里就已经完成了,Spring Boot会在侦测到存在Redis的依赖并且Redis的配置是可用的情况下,使用RedisCacheManager初始化CacheManager

为此,我们可以单步运行我们的单元测试,可以观察到此时CacheManager的实例是org.springframework.data.redis.cache.RedisCacheManager,并获得下面的执行结果:

 
    
1
2
3
4
5
6
7
 
    
Hibernate: insert into user (age, name) values (?, ?)
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=?
第一次查询:10
第二次查询:10
Hibernate: select user0_.id as id1_0_0_, user0_.age as age2_0_0_, user0_.name as name3_0_0_ from user user0_ where user0_.id=?
Hibernate: update user set age=?, name=? where id=?
第三次查询:10

可以观察到,在第一次查询的时候,执行了select语句;第二次查询没有执行select语句,说明是从缓存中获得了结果;而第三次查询,我们获得了一个错误的结果,根据我们的测试逻辑,在查询之前我们已经将age更新为20,但是我们从缓存中获取到的age还是为10。

问题思考

为什么同样的逻辑在EhCache中没有问题,但是到Redis中会出现这个问题呢?

在EhCache缓存时没有问题,主要是由于EhCache是进程内的缓存框架,第一次通过select查询出的结果被加入到EhCache缓存中,第二次查询从EhCache取出的对象与第一次查询对象实际上是同一个对象(可以在使用Chapter4-4-1工程中,观察u1==u2来看看是否是同一个对象),因此我们在更新age的时候,实际已经更新了EhCache中的缓存对象。

而Redis的缓存独立存在于我们的Spring应用之外,我们对数据库中数据做了更新操作之后,没有通知Redis去更新相应的内容,因此我们取到了缓存中未修改的数据,导致了数据库与缓存中数据的不一致。

因此我们在使用缓存的时候,要注意缓存的生命周期,利用好上一篇上提到的几个注解来做好缓存的更新、删除

进一步修改

针对上面的问题,我们只需要在更新age的时候,通过@CachePut来让数据更新操作同步到缓存中,就像下面这样:

 
    
1
2
3
4
5
6
7
8
9
10
 
    
@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long> {
@Cacheable(key = "#p0")
User findByName(String name);
@CachePut(key = "#p0.name")
User save(User user);
}

在redis-cli中flushdb,清空一下之前的缓存内容,再执行单元测试,可以获得下面的结果:

 
    
1
2
3
4
5
6
 
    
Hibernate: insert into user (age, name) values (?, ?)
第一次查询:10
第二次查询:10
Hibernate: select user0_.id as id1_0_0_, user0_.age as age2_0_0_, user0_.name as name3_0_0_ from user user0_ where user0_.id=?
Hibernate: update user set age=?, name=? where id=?
第三次查询:20

可以看到,我们的第三次查询获得了正确的结果!同时,我们的第一次查询也不是通过select查询获得的,因为在初始化数据的时候,调用save方法时,就已经将这条数据加入了redis缓存中,因此后续的查询就直接从redis中获取了。

本文内容到此为止,主要介绍了为什么要使用Redis做缓存,以及如何在Spring Boot中使用Redis做缓存,并且通过一个小问题来帮助大家理解缓存机制,在使用过程中,一定要注意缓存生命周期的控制,防止数据不一致的情况出现。

完整示例:Chapter-4-4-2


Spring Boot中的缓存支持(一)注解配置与EhCache使用

随着时间的积累,应用的使用用户不断增加,数据规模也越来越大,往往数据库查询操作会成为影响用户使用体验的瓶颈,此时使用缓存往往是解决这一问题非常好的手段之一。Spring 3开始提供了强大的基于注解的缓存支持,可以通过注解配置方式低侵入的给原有Spring应用增加缓存功能,提高数据访问性能。

在Spring Boot中对于缓存的支持,提供了一系列的自动化配置,使我们可以非常方便的使用缓存。下面我们通过一个简单的例子来展示,我们是如何给一个既有应用增加缓存功能的。

快速入门

首先,下载样例工程chapter3-2-2。本例通过spring-data-jpa实现了对User用户表的一些操作,若没有这个基础,可以先阅读《使用Spring-data-jpa简化数据访问层》一文对数据访问有所基础。

准备工作

为了更好的理解缓存,我们先对该工程做一些简单的改造。

  • application.properties文件中新增spring.jpa.properties.hibernate.show_sql=true,开启hibernate对sql语句的打印

  • 修改单元测试ApplicationTests,初始化插入User表一条用户名为AAA,年龄为10的数据。并通过findByName函数完成两次查询。

 
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 
    
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTests {
@Autowired
private UserRepository userRepository;
@Before
public void before() {
userRepository.save( new User( "AAA", 10));
}
@Test
public void test() throws Exception {
User u1 = userRepository.findByName( "AAA");
System.out.println( "第一次查询:" + u1.getAge());
User u2 = userRepository.findByName( "AAA");
System.out.println( "第二次查询:" + u2.getAge());
}
}
  • 执行单元测试,我们可以在控制台中看到下面内容。
 
    
1
2
3
4
5
 
    
Hibernate: insert into user (age, name) values (?, ?)
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=?
第一次查询:10
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=?
第二次查询:10

在测试用例执行前,插入了一条User记录。然后每次findByName调用时,都执行了一句select语句来查询用户名为AAA的记录。

引入缓存
  • pom.xml中引入cache依赖,添加如下内容:
 
    
1
2
3
4
 
    
<dependency>
<groupId>org.springframework.boot </groupId>
<artifactId>spring-boot-starter-cache </artifactId>
</dependency>
  • 在Spring Boot主类中增加@EnableCaching注解开启缓存功能,如下:
 
    
1
2
3
4
5
6
7
8
9
 
    
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
  • 在数据访问接口中,增加缓存配置注解,如:
 
    
1
2
3
4
5
6
7
 
    
@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long> {
@Cacheable
User findByName(String name);
}
  • 再来执行以下单元测试,可以在控制台中输出了下面的内容:
 
    
1
2
3
4
 
    
Hibernate: insert into user (age, name) values (?, ?)
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=?
第一次查询:10
第二次查询:10

到这里,我们可以看到,在调用第二次findByName函数时,没有再执行select语句,也就直接减少了一次数据库的读取操作。

为了可以更好的观察,缓存的存储,我们可以在单元测试中注入cacheManager。

 
    
1
2
 
    
@Autowired
private CacheManager cacheManager;

使用debug模式运行单元测试,观察cacheManager中的缓存集users以及其中的User对象的缓存加深理解。

Cache注解详解

回过头来我们再来看,这里使用到的两个注解分别作了什么事情。

  • @CacheConfig:主要用于配置该类中会用到的一些共用的缓存配置。在这里@CacheConfig(cacheNames = "users"):配置了该数据访问对象中返回的内容将存储于名为users的缓存对象中,我们也可以不使用该注解,直接通过@Cacheable自己配置缓存集的名字来定义。

  • @Cacheable:配置了findByName函数的返回值将被加入缓存。同时在查询时,会先从缓存中获取,若不存在才再发起对数据库的访问。该注解主要有下面几个参数:

    • valuecacheNames:两个等同的参数(cacheNames为Spring 4新增,作为value的别名),用于指定缓存存储的集合名。由于Spring 4中新增了@CacheConfig,因此在Spring 3中原本必须有的value属性,也成为非必需项了
    • key:缓存对象存储在Map集合中的key值,非必需,缺省按照函数的所有参数组合作为key值,若自己配置需使用SpEL表达式,比如:@Cacheable(key = "#p0"):使用函数第一个参数作为缓存的key值,更多关于SpEL表达式的详细内容可参考官方文档
    • condition:缓存对象的条件,非必需,也需使用SpEL表达式,只有满足表达式条件的内容才会被缓存,比如:@Cacheable(key = "#p0", condition = "#p0.length() < 3"),表示只有当第一个参数的长度小于3的时候才会被缓存,若做此配置上面的AAA用户就不会被缓存,读者可自行实验尝试。
    • unless:另外一个缓存条件参数,非必需,需使用SpEL表达式。它不同于condition参数的地方在于它的判断时机,该条件是在函数被调用之后才做判断的,所以它可以通过对result进行判断。
    • keyGenerator:用于指定key生成器,非必需。若需要指定一个自定义的key生成器,我们需要去实现org.springframework.cache.interceptor.KeyGenerator接口,并使用该参数来指定。需要注意的是:该参数与key是互斥的
    • cacheManager:用于指定使用哪个缓存管理器,非必需。只有当有多个时才需要使用
    • cacheResolver:用于指定使用那个缓存解析器,非必需。需通过org.springframework.cache.interceptor.CacheResolver接口来实现自己的缓存解析器,并用该参数指定。

除了这里用到的两个注解之外,还有下面几个核心注解:

  • @CachePut:配置于函数上,能够根据参数定义条件来进行缓存,它与@Cacheable不同的是,它每次都会真是调用函数,所以主要用于数据新增和修改操作上。它的参数与@Cacheable类似,具体功能可参考上面对@Cacheable参数的解析
  • @CacheEvict:配置于函数上,通常用在删除方法上,用来从缓存中移除相应数据。除了同@Cacheable一样的参数之外,它还有下面两个参数:
    • allEntries:非必需,默认为false。当为true时,会移除所有数据
    • beforeInvocation:非必需,默认为false,会在调用方法之后移除数据。当为true时,会在调用方法之前移除数据。

缓存配置

完成了上面的缓存实验之后,可能大家会问,那我们在Spring Boot中到底使用了什么缓存呢?

在Spring Boot中通过@EnableCaching注解自动化配置合适的缓存管理器(CacheManager),Spring Boot根据下面的顺序去侦测缓存提供者:

  • Generic
  • JCache (JSR-107)
  • EhCache 2.x
  • Hazelcast
  • Infinispan
  • Redis
  • Guava
  • Simple

除了按顺序侦测外,我们也可以通过配置属性spring.cache.type来强制指定。我们可以通过debug调试查看cacheManager对象的实例来判断当前使用了什么缓存。

本文中不对所有的缓存做详细介绍,下面以常用的EhCache为例,看看如何配置来使用EhCache进行缓存管理。

在Spring Boot中开启EhCache非常简单,只需要在工程中加入ehcache.xml配置文件并在pom.xml中增加ehcache依赖,框架只要发现该文件,就会创建EhCache的缓存管理器。

  • src/main/resources目录下创建:ehcache.xml
 
    
1
2
3
4
5
6
7
8
9
 
    
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation= "ehcache.xsd">
<cache name="users"
maxEntriesLocalHeap= "200"
timeToLiveSeconds= "600">
</cache>
</ehcache>
  • pom.xml中加入
 
    
1
2
3
4
 
    
<dependency>
<groupId>net.sf.ehcache </groupId>
<artifactId>ehcache </artifactId>
</dependency>

完成上面的配置之后,再通过debug模式运行单元测试,观察此时CacheManager已经是EhCacheManager实例,说明EhCache开启成功了。

对于EhCache的配置文件也可以通过application.properties文件中使用spring.cache.ehcache.config属性来指定,比如:

 
    
1
 
    
spring.cache.ehcache.config=classpath:config/another-config.xml

完整示例:Chapter-4-4-1

Spring Cloud构建微服务架构(三)断路器


在微服务架构中,我们将系统拆分成了一个个的服务单元,各单元间通过服务注册与订阅的方式互相依赖。由于每个单元都在不同的进程中运行,依赖通过远程调用的方式执行,这样就有可能因为网络原因或是依赖服务自身问题出现调用故障或延迟,而这些问题会直接导致调用方的对外服务也出现延迟,若此时调用方的请求不断增加,最后就会出现因等待出现故障的依赖方响应而形成任务积压,最终导致自身服务的瘫痪。

举个例子,在一个电商网站中,我们可能会将系统拆分成,用户、订单、库存、积分、评论等一系列的服务单元。用户创建一个订单的时候,在调用订单服务创建订单的时候,会向库存服务来请求出货(判断是否有足够库存来出货)。此时若库存服务因网络原因无法被访问到,导致创建订单服务的线程进入等待库存申请服务的响应,在漫长的等待之后用户会因为请求库存失败而得到创建订单失败的结果。如果在高并发情况之下,因这些等待线程在等待库存服务的响应而未能释放,使得后续到来的创建订单请求被阻塞,最终导致订单服务也不可用。

在微服务架构中,存在着那么多的服务单元,若一个单元出现故障,就会因依赖关系形成故障蔓延,最终导致整个系统的瘫痪,这样的架构相较传统架构就更加的不稳定。为了解决这样的问题,因此产生了断路器模式。

什么是断路器

断路器模式源于Martin Fowler的Circuit Breaker一文。“断路器”本身是一种开关装置,用于在电路上保护线路过载,当线路中有电器发生短路时,“断路器”能够及时的切断故障电路,防止发生过载、发热、甚至起火等严重后果。

在分布式架构中,断路器模式的作用也是类似的,当某个服务单元发生故障(类似用电器发生短路)之后,通过断路器的故障监控(类似熔断保险丝),向调用方返回一个错误响应,而不是长时间的等待。这样就不会使得线程因调用故障服务被长时间占用不释放,避免了故障在分布式系统中的蔓延。

Netflix Hystrix

在Spring Cloud中使用了Hystrix来实现断路器的功能。Hystrix是Netflix开源的微服务框架套件之一,该框架目标在于通过控制那些访问远程系统、服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。Hystrix具备拥有回退机制和断路器功能的线程和信号隔离,请求缓存和请求打包,以及监控和配置等功能。

下面我们来看看如何使用Hystrix。

准备工作

在开始加入断路器之前,我们先拿之前构建两个微服务为基础进行下面的操作,主要使用下面几个工程:

  • chapter9-1-1
    • eureka-server工程:服务注册中心,端口1111
    • compute-service工程:服务单元,端口2222
  • chapter9-1-2
    • eureka-ribbon:通过ribbon实现的服务单元,依赖compute-service的服务,端口3333
    • eureka-feign:通过feign实现的服务单元,依赖compute-service的服务,端口3333

若您还没有使用Spring Cloud的经验,可以先阅读《服务注册与发现》《服务消费者》,对Spring Cloud构建的微服务有一个初步的认识。

Ribbon中引入Hystrix
  • 依次启动eureka-server、compute-service、eureka-ribbon工程
  • 访问http://localhost:1111/可以看到注册中心的状态
  • 访问http://localhost:3333/add,调用eureka-ribbon的服务,该服务会去调用compute-service的服务,计算出10+20的值,页面显示30
  • 关闭compute-service服务,访问http://localhost:3333/add,我们获得了下面的报错信息
 
    
1
2
3
4
5
6
7
 
    
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Jun 25 21:16:59 CST 2016
There was an unexpected error ( type=Internal Server Error, status=500).
I/O error on GET request for "http://COMPUTE-SERVICE/add?a=10&b=20": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
  • pom.xml中引入依赖hystrix依赖
 
    
1
2
3
4
 
    
<dependency>
<groupId>org.springframework.cloud </groupId>
<artifactId>spring-cloud-starter-hystrix </artifactId>
</dependency>
  • 在eureka-ribbon的主类RibbonApplication中使用@EnableCircuitBreaker注解开启断路器功能:
 
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
    
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class RibbonApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class, args);
}
}
  • 改造原来的服务消费方式,新增ComputeService类,在使用ribbon消费服务的函数上增加@HystrixCommand注解来指定回调方法。
 
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
    
@Service
public class ComputeService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "addServiceFallback")
public String addService() {
return restTemplate.getForEntity( "http://COMPUTE-SERVICE/add?a=10&b=20", String.class).getBody();
}
public String addServiceFallback() {
return "error";
}
}
  • 提供rest接口的Controller改为调用ComputeService的addService
 
    
1
2
3
4
5
6
7
8
9
10
11
12
 
    
@RestController
public class ConsumerController {
@Autowired
private ComputeService computeService;
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String add() {
return computeService.addService();
}
}

更多关于Hystrix的使用可参考How To Use

Feign使用Hystrix

注意这里说的是“使用”,没有错,我们不需要在Feigh工程中引入Hystix,Feign中已经依赖了Hystrix,我们可以在未做任何改造前,尝试下面你的操作:

  • 依次启动eureka-server、compute-service、eureka-feign工程
  • 访问http://localhost:1111/可以看到注册中心的状态
  • 访问http://localhost:3333/add,调用eureka-feign的服务,该服务会去调用compute-service的服务,计算出10+20的值,页面显示30
  • 关闭compute-service服务,访问http://localhost:3333/add,我们获得了下面的报错信息
 
    
1
2
3
4
5
6
7
 
    
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Jun 25 22:10:05 CST 2016
There was an unexpected error ( type=Internal Server Error, status=500).
add timed-out and no fallback available.

如果您够仔细,会发现与在ribbon中的报错是不同的,看到add timed-out and no fallback available这句,或许您已经猜到什么,看看我们的控制台,可以看到报错信息来自hystrix-core-1.5.2.jar,所以在这个工程中,我们要学习的就是如何使用Feign中集成的Hystrix。

  • 使用@FeignClient注解中的fallback属性指定回调类
 
    
1
2
3
4
5
6
7
 
    
@FeignClient(value = "compute-service", fallback = ComputeClientHystrix.class)
public interface ComputeClient {
@RequestMapping(method = RequestMethod.GET, value = "/add")
Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value = "b") Integer b);
}
  • 创建回调类ComputeClientHystrix,实现@FeignClient的接口,此时实现的方法就是对应@FeignClient接口中映射的fallback函数。
 
    
1
2
3
4
5
6
7
8
9
 
    
@Component
public class ComputeClientHystrix implements ComputeClient {
@Override
public Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value = "b") Integer b) {
return - 9999;
}
}
  • 再用之前的方法验证一下,是否在compute-service服务不可用的情况下,页面返回了-9999。

关于Feign的更多使用方法可参考:Feign

Spring Cloud构建微服务架构(二)服务消费者


Ribbon

Ribbon是一个基于HTTP和TCP客户端的负载均衡器。Feign中也使用Ribbon,后续会介绍Feign的使用。

Ribbon可以在通过客户端中配置的ribbonServerList服务端列表去轮询访问以达到均衡负载的作用。

当Ribbon与Eureka联合使用时,ribbonServerList会被DiscoveryEnabledNIWSServerList重写,扩展成从Eureka注册中心中获取服务端列表。同时它也会用NIWSDiscoveryPing来取代IPing,它将职责委托给Eureka来确定服务端是否已经启动。

下面我们通过实例看看如何使用Ribbon来调用服务,并实现客户端的均衡负载。

准备工作
  • 启动Chapter-9-1-1中的服务注册中心:eureka-server
  • 启动Chapter-9-1-1中的服务提供方:compute-service
  • 修改compute-service中的server-port为2223,再启动一个服务提供方:compute-service

此时访问:http://localhost:1111/

altalt

可以看到COMPUTE-SERVICE服务有两个单元正在运行:

  • 192.168.21.101:compute-service:2222
  • 192.168.21.101:compute-service:2223
使用Ribbon实现客户端负载均衡的消费者

构建一个基本Spring Boot项目,并在pom.xml中加入如下内容:

 
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 
    
<parent>
<groupId>org.springframework.boot </groupId>
<artifactId>spring-boot-starter-parent </artifactId>
<version>1.3.5.RELEASE </version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud </groupId>
<artifactId>spring-cloud-starter-ribbon </artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud </groupId>
<artifactId>spring-cloud-starter-eureka </artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot </groupId>
<artifactId>spring-boot-starter-web </artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot </groupId>
<artifactId>spring-boot-starter-test </artifactId>
<scope>test </scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud </groupId>
<artifactId>spring-cloud-dependencies </artifactId>
<version>Brixton.RELEASE </version>
<type>pom </type>
<scope>import </scope>
</dependency>
</dependencies>
</dependencyManagement>

在应用主类中,通过@EnableDiscoveryClient注解来添加发现服务能力。创建RestTemplate实例,并通过@LoadBalanced注解开启均衡负载能力。

 
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
    
@SpringBootApplication
@EnableDiscoveryClient
public class RibbonApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class, args);
}
}

创建ConsumerController来消费COMPUTE-SERVICE的add服务。通过直接RestTemplate来调用服务,计算10 + 20的值。

 
    
1
2
3
4
5
6
7
8
9
10
11
12
 
    
@RestController
public class ConsumerController {
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String add() {
return restTemplate.getForEntity( "http://COMPUTE-SERVICE/add?a=10&b=20", String.class).getBody();
}
}

application.properties中配置eureka服务注册中心

 
    
1
2
3
4
5
 
    
spring.application.name=ribbon-consumer
server.port=3333
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/

启动该应用,并访问两次:http://localhost:3333/add

然后,打开compute-service的两个服务提供方,分别输出了类似下面的日志内容:

  • 端口为2222服务提供端的日志:
 
    
1
 
    
2016-06-02 11:16:26.787 INFO 90014 --- [io-2222-exec-10] com.didispace.web.ComputeController : /add, host:192.168.21.101, service_id:compute-service, result:30
  • 端口为2223服务提供端的日志:
 
    
1
 
    
2016-06-02 11:19:41.241 INFO 90122 --- [nio-2223-exec-1] com.didispace.web.ComputeController : /add, host:192.168.21.101, service_id:compute-service, result:30

可以看到,之前启动的两个compute-service服务端分别被调用了一次。到这里,我们已经通过Ribbon在客户端已经实现了对服务调用的均衡负载。

完整示例可参考:Chapter9-1-2/eureka-ribbon

Feign

Feign是一个声明式的Web Service客户端,它使得编写Web Serivce客户端变得更加简单。我们只需要使用Feign来创建一个接口并用注解来配置它既可完成。它具备可插拔的注解支持,包括Feign注解和JAX-RS注解。Feign也支持可插拔的编码器和解码器。Spring Cloud为Feign增加了对Spring MVC注解的支持,还整合了Ribbon和Eureka来提供均衡负载的HTTP客户端实现。

下面,通过一个例子来展现Feign如何方便的声明对上述computer-service服务的定义和调用。

创建一个Spring Boot工程,配置pom.xml,将上述的配置中的ribbon依赖替换成feign的依赖即可,具体如下:

 
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 
    
<parent>
<groupId>org.springframework.boot </groupId>
<artifactId>spring-boot-starter-parent </artifactId>
<version>1.3.5.RELEASE </version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud </groupId>
<artifactId>spring-cloud-starter-feign </artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud </groupId>
<artifactId>spring-cloud-starter-eureka </artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot </groupId>
<artifactId>spring-boot-starter-web </artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot </groupId>
<artifactId>spring-boot-starter-test </artifactId>
<scope>test </scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud </groupId>
<artifactId>spring-cloud-dependencies </artifactId>
<version>Brixton.RELEASE </version>
<type>pom </type>
<scope>import </scope>
</dependency>
</dependencies>
</dependencyManagement>

在应用主类中通过@EnableFeignClients注解开启Feign功能,具体如下:

 
    
1
2
3
4
5
6
7
8
9
10
 
    
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class FeignApplication {
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class, args);
}
}

定义compute-service服务的接口,具体如下:

 
    
1
2
3
4
5
6
7
 
    
@FeignClient( "compute-service")
public interface ComputeClient {
@RequestMapping(method = RequestMethod.GET, value = "/add")
Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value = "b") Integer b);
}
  • 使用@FeignClient("compute-service")注解来绑定该接口对应compute-service服务
  • 通过Spring MVC的注解来配置compute-service服务下的具体实现。

在web层中调用上面定义的ComputeClient,具体如下:

 
    
1
2
3
4
5
6
7
8
9
10
11
12
 
    
@RestController
public class ConsumerController {
@Autowired
ComputeClient computeClient;
@RequestMapping(value = "/add", method = RequestMethod.GET)
public Integer add() {
return computeClient.add( 10, 20);
}
}

application.properties中不用变,指定eureka服务注册中心即可,如:

 
    
1
2
3
4
 
    
spring.application.name=feign-consumer
server.port=3333
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/

启动该应用,访问几次:http://localhost:3333/add

再观察日志,可以得到之前使用Ribbon时一样的结果,对服务提供方实现了均衡负载。

这一节我们通过Feign以接口和注解配置的方式,轻松实现了对compute-service服务的绑定,这样我们就可以在本地应用中像本地服务一下的调用它,并且做到了客户端均衡负载。

完整示例可参考:Chapter9-1-2/eureka-feign


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值