redisTemplate的使用

<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>2.0.7.RELEASE</version>
</dependency>

import org.springframework.beans.factory.annotation.Autowired;
    @Autowired
    private RedisTemplate           redisTemplate;
	
	 //获取token
    private String getToken() {
        String token="";
        //查询redis是否有token
        ValueOperations ops = redisTemplate.opsForValue();
        token = (String) ops.get("token");
        if (StringUtils.isBlank(token)) {
            // 设置请求头
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            headers.put("accept", "application/json; charset=utf-8");
            String client_id = "P_OKAY001";
            String client_secret = "VuVEh743";
            JSONObject js = JSONObject.parseObject(doPost(
                    "https://test-api.pingan.com.cn:20443/oauth/oauth2/access_token?client_id=" + client_id + "&grant_type=client_credentials&client_secret=" + client_secret,
                    null, headers));
            token = ((JSONObject) js.get("data")).getString("access_token");
            ops.set("token",token,24, TimeUnit.HOURS);
        }
        return token;
    }

Redis的String数据结构

ValueOperations可以对String数据结构进行操作:

  • set void set(K key, V value);

    使用:redisTemplate.opsForValue().set("name","tom");
    结果:redisTemplate.opsForValue().get("name")  输出结果为tom
  • set void set(K key, V value, long timeout, TimeUnit unit);

    使用:redisTemplate.opsForValue().set("name","tom",10, TimeUnit.SECONDS);
    结果:redisTemplate.opsForValue().get("name")由于设置的是10秒失效,十秒之内查询有结果,十秒之后返回为null

猜你喜欢

转载自blog.csdn.net/qq_39940205/article/details/80455727