package com.yp.api.core.api;
import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.client.RestClientException;
import yp.web.client.RestTemplate;
public class ApiTemplate
{
private RestTemplate restTemplate;
private RedisTemplate redisTemplate;
public void setRestTemplate(RestTemplate restTemplate)
{
this.restTemplate = restTemplate;
}
public void setRedisTemplate(RedisTemplate redisTemplate)
{
this.redisTemplate = redisTemplate;
}
/**
*
* @param url
* @param expire 毫秒数
* @param responseType
* @param urlVariables
* @return
* @throws RestClientException
*/
public <T> T getForObject(String url,int expire, Class<T> responseType, Object... urlVariables) throws RestClientException {
if(expire>0)
{
ValueOperations<String, T> valueOper = redisTemplate.opsForValue();
T t= valueOper.get(url);
if(t!=null)
{
System.out.println(url+"命中缓存");
return t;
}else
{
t=restTemplate.getForObject(url, responseType, urlVariables);
valueOper.set(url, t,expire,TimeUnit.SECONDS);
return t;
}
}
else
{
return restTemplate.getForObject(url, responseType, urlVariables);
}
}
public <T> T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables) throws RestClientException {
return restTemplate.postForObject(url, request, responseType, uriVariables);
}
public void put(String key,Object value,int expire)
{
ValueOperations<String, Object> valueOper = redisTemplate.opsForValue();
valueOper.set(key, value,expire,TimeUnit.SECONDS);
}
public Object get(String key){
ValueOperations<String, Object> valueOper = redisTemplate.opsForValue();
return valueOper.get(key);
}
}