<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
spring:
redis:
host: 192.168.10.110
port: 6379
jedis:
pool:
enabled: true
min-idle: 8
max-active: 8
max-wait: 5s
@Slf4j
@Component
public class OrganizationRestTemplateClient {
private RestTemplate restTemplate;
private OrganizationRedisRepository redisRepository;
private Organization checkRedisCache(String organizationId) {
try {
return redisRepository
.findById(organizationId)
.orElse(null);
} catch (Exception ex) {
log.error("Error encountered while trying to retrieve organization{} check Redis Cache. Exception {}",
organizationId, ex);
return null;
}
}
private void cacheOrganizationObject(Organization organization) {
try {
redisRepository.save(organization);
} catch (Exception ex) {
log.error("Unable to cache organization {} in Redis.Exception {}",
organization.getId(), ex);
}
}
public Organization getOrganization(String organizationId) {
log.debug("In Licensing Service.getOrganization: {}",
UserContextHolder.getContext().getCorrelationId());
Organization organization = checkRedisCache(organizationId);
if (organization != null) {
log.debug("I have successfully retrieved an organization {} from the redis cache: {}",
organizationId, organization);
return organization;
}
log.debug("Unable to locate organization from the redis cache:{}.", organizationId);
organization = restTemplate.getForObject(
"http://{applicationId}/v1/organization/{organizationId}",
Organization.class,
"organization-service",
organizationId);
if (organization != null) {
cacheOrganizationObject(organization);
}
return organization;
}
@Autowired
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Autowired
public void setRedisRepository(OrganizationRedisRepository redisRepository) {
this.redisRepository = redisRepository;
}
}
注意:
在与缓存交互时要特别注意异常处理。
为了增加弹性,当无法与Redis服务器通信时,我们并未让调用失败。相反,我们记录异常并允许调用到达组织服务。在这种特定情况下,缓存旨在帮助提高性能,而缓存服务器的缺失并不影响调用的成功。