微信分享签名后台缓存token,使用文件方式

完成签名后台之后,其实目前每天2000已经够用了,但还是完善一下。

设计思想就是加一个判断,因为从公众号中获取的token的保鲜期就两个小时,也就是7200s,如果还新鲜,就在文件中取,如果不新鲜,就重新请求微信获取token,然后把新的token存到文件中,并更新获取token的时间。

其实就是把token和时间存一下,使用文件、数据库都可以实现,我用的是文件。

先说文件,我是使用.properties文件,然后里面有两个键值,一个token用来存放token的值,一个是time用来存放取token的时间,我存放的是通过System.currentTimeMillis();获取的毫秒数。
文件token.properties

token=1111
time=22222

工具类readAndwirte,java

import java.util.Properties;
import java.util.Enumeration;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class readAndwrite {
	 //读取信息
	public static String readBykey(String filePath, String key) {
        Properties p = new Properties();
        try {
            InputStream in = new BufferedInputStream (new FileInputStream(filePath));  
            p.load(in);
            String value = p.getProperty(key);
            return value;
        }catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    //写入信息
    public static void WriteBykey (String filePath, String Key, String Value) throws IOException {
        Properties p = new Properties();
        InputStream in = new FileInputStream(filePath);
        //从输入流中读取属性列表(键和元素对) 
        p.load(in);
        //调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。  
        //强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
        OutputStream out = new FileOutputStream(filePath);
        p.setProperty(Key, Value);
        //以适合使用 load 方法加载到 Properties 表中的格式,  
        //将此 Properties 表中的属性列表(键和元素对)写入输出流  
        p.store(out, "Update " + Key + " name");
    }
}

因为每个人的业务不同,所以只给出使用的例子example.java思路就是当前毫秒和获取token时候的毫秒/1000相减看是否大于7200。

public String example {
		//地址是绝对地址
		long getoldtime = Long.parseLong(readAndwrite.GetValueByKey("C:/token/token.properties","time"));
		long currentTimeMillis = System.currentTimeMillis();
		if((currentTimeMillis-getoldtime)/1000>7200){
			accessToken = getAccessToken();//你定义的请求微信服务器获取token的方法
			try {
				readAndwrite.WriteProperties("C:/token/token.properties","token", accessToken);
				readAndwrite.WriteProperties("C:/token/token.properties","time", String.valueOf(currentTimeMillis));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			accessToken=readAndwrite.GetValueByKey("C:/token/token.properties","token");
		}
		return token;
	}

需要注意的是,在写入和读出的时候传的地址是绝对地址,所以你本地和部署到服务器上的地址是不同的,这要注意一下,要不然404。
最后感谢:读取写入的例子。
https://blog.csdn.net/qy20115549/article/details/73368611

发布了64 篇原创文章 · 获赞 103 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/P_Doraemon/article/details/89678925