springcloud集成redis

1. pom.xml里面添加redis的maven依赖

 
          org.springframework.data
          spring-data-redis
          1.7.4.RELEASE
      

      
          redis.clients
          jedis
          2.9.0
      

      
          org.apache.commons
          commons-pool2
          2.0
      

2. properties 配置

redis.server: "localhost"
redis.port: "6379"

3. 代码

@Bean
    public JedisConnectionFactory jedisConnectionFactory(){
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setHostName("localhost");
        jedisConnectionFactory.setPort(6379);
        return jedisConnectionFactory;
    }

    @Bean
    public RedisTemplate redisTemplate(){
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        return template;
    }

import com.thoughtmechanix.licenses.model.Organization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
//实体类implements Serializable
@Repository
public class OrganizationRedisRepositoryImpl implements OrganizationRedisRepository {
	private static final String HASH_NAME = "organization";
	
	@Autowired
	private RedisTemplate redisTemplate;

	private HashOperations hashOperations;

	@PostConstruct
	private void init(){
		hashOperations = redisTemplate.opsForHash();
	}
	@Override
	public void saveOrganization(Organization org) {
		hashOperations.put(HASH_NAME,org.getId(),org);
	}

	@Override
	public void updateOrganization(Organization org) {
		hashOperations.put(HASH_NAME,org.getId(),org);
	}

	@Override
	public void deleteOrganization(String organizationId) {
		hashOperations.delete(HASH_NAME,organizationId);
	}

	@Override
	public Organization findOrganization(String organizationId) {
		return (Organization)hashOperations.get(HASH_NAME,organizationId);
	}
}

import com.thoughtmechanix.licenses.model.Organization;
import com.thoughtmechanix.licenses.repository.OrganizationRedisRepository;
import com.thoughtmechanix.licenses.utils.UserContext;
import com.thoughtmechanix.licenses.utils.UserContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class OrganizationRestTemplateClient {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    OrganizationRedisRepository orgRedisRepo;

    private static final Logger logger = LoggerFactory.getLogger(OrganizationRestTemplateClient.class);

    private Organization checkRedisCache(String organizationId) {
        try {
            return orgRedisRepo.findOrganization(organizationId);
        }
        catch (Exception ex){
            logger.error("Error encountered while trying to retrieve organization {} check Redis Cache.  Exception {}", organizationId, ex);
            return null;
        }
    }

    private void cacheOrganizationObject(Organization org) {
        try {
            orgRedisRepo.saveOrganization(org);
        }catch (Exception ex){
            logger.error("Unable to cache organization {} in Redis. Exception {}", org.getId(), ex);
        }
    }

    public Organization getOrganization(String organizationId){
        logger.debug("In Licensing Service.getOrganization: {}", UserContext.getCorrelationId());
        Organization org = checkRedisCache(organizationId);
        if (org!=null){
            logger.debug("I have successfully retrieved an organization {} from the redis cache: {}", organizationId, org);
            return org;
        }
        logger.debug("Unable to locate organization from the redis cache: {}.", organizationId);

        ResponseEntity restExchange =
                restTemplate.exchange(
                        "http://zuulservice/api/organization/v1/organizations/{organizationId}",
                        HttpMethod.GET,
                        null, Organization.class, organizationId);

        org = restExchange.getBody();
        if(org!=null){
            cacheOrganizationObject(org);
        }
        return org;
    }
}

你可能感兴趣的:(springcloud,redis)