redis配置如下
var ioc = {
// 参考 https://github.com/xetorthio/jedis/wiki/Getting-started
jedisPoolConfig : {
type : "redis.clients.jedis.JedisPoolConfig",
fields : {
testWhileIdle : true, // 空闲时测试,免得redis连接空闲时间长了断线
maxTotal : 100 // 一般都够了吧
}
},
jedisPool : {
type : "redis.clients.jedis.JedisPool",
args : [
{refer : "jedisPoolConfig"},
// 从配置文件中读取redis服务器信息
{java : "$conf.get('redis.host', 'localhost')"},
{java : "$conf.getInt('redis.port', 6379)"},
{java : "$conf.getInt('redis.timeout', 2000)"},
{java : "$conf.get('redis.password')"},
],
fields : {},
events : {
depose : "destroy" // 关闭应用时必须关掉呢
}
}
};
@IocBean(args = {"refer:dao"})
public class ApiService extends Service<Sys_api> {
private static final Log log = Logs.get();
public ApiService(Dao dao) {
super(dao);
}
private static final String at="accessToken";
public static Key key;
/**
* 生成token
* Key以字节流形式存入redis
*
* @param date 失效时间
* @param appId AppId
* @return
*/
@Aop("redis")
public String generateToken(Date date, String appId){
try{
byte[] buf = jedis().get("api:key".getBytes());
if (buf == null) { // 建新的key
key = MacProvider.generateKey();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bao);
oos.writeObject(key);
buf = bao.toByteArray();
jedis().set("api:key".getBytes(), buf);
} else { // 重用老key
key = (Key) new ObjectInputStream(new ByteArrayInputStream(buf)).readObject();
}
}catch (IOException io){
System.out.println(io);
}catch (ClassNotFoundException c){
System.out.println(c);
}
String token = Jwts.builder()
.setSubject(appId)
.signWith(SignatureAlgorithm.HS512, key)
.setExpiration(date)
.compact();
// 计算失效秒,7889400秒三个月
Date temp = new Date();
long interval = (date.getTime() - temp.getTime())/1000;
jedis().setex(at+appId ,(int)interval,token);
return token;
}
/**
* 验证token
* @param appId AppId
* @param token token
* @return
*/
@Aop("redis")
public boolean verifyToken(String appId, String token) {
try {
if (key == null) {
byte[] buf = jedis().get("api:key".getBytes());
if(buf==null){
return false;
}
key = (Key) new ObjectInputStream(new ByteArrayInputStream(buf)).readObject();
}
Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject().equals(appId);
return true;
} catch (Exception e) {
log.debug(e.getMessage());
return false;
}
}
/**
* 获取token
* @param appId
* @return
*/
@Aop("redis")
public String getToken(String appId) {
return jedis().get(at+appId);
}
/**
* 验证会员ID,用于首页接口、产品查看、收藏等接口
* @param appId
* @return
*/
public boolean verifyId(String appId) {
try {
App_user user = dao().fetch(App_user.class, Cnd.where("id","=",Long.parseLong(appId)));
if (user!=null){
return true;
}else {
return false;
}
} catch (Exception e) {
log.debug(e.getMessage());
return false;
}
}