Redis缓存简单示例

1.jar包:

Springboot框架用这个会比较好



    org.springframework.boot
    spring-boot-starter-data-redis
    1.5.9.RELEASE

通用的用:



    redis.clients
    jedis
    2.9.0

这里测试一下就只放入一个key和value了

Redis缓存简单示例_第1张图片

 

 

 

 

 

接口,声明方法

 

 

fRedis缓存简单示例_第2张图片

 

 

@Service("redisService")
public class RedisServiceImpl implements RedisService {

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private JedisPool jedisPool;

    public boolean set(final String key, final String value) {
        boolean result = redisTemplate.execute(new RedisCallback() {
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer serializer = redisTemplate.getStringSerializer();
                connection.set(serializer.serialize(key), serializer.serialize(value));
                return true;
            }
        });
        return result;
    }

    public boolean set(final String key, final String value, final Long expireTime) {
        boolean result = redisTemplate.execute(new RedisCallback() {
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer serializer = redisTemplate.getStringSerializer();
                connection.set(serializer.serialize(key), serializer.serialize(value));
                redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
                return true;
            }
        });
        return result;
    }

    public String get(final String key) {
        String result = redisTemplate.execute(new RedisCallback() {
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer serializer = redisTemplate.getStringSerializer();
                byte[] value = connection.get(serializer.serialize(key));
                return serializer.deserialize(value);
            }
        });
        return result;
    }

    public boolean exists(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.exists(key);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    @Override
    public void delete(String key) {
        try{
            Jedis jedis = jedisPool.getResource();
            jedis.del(key);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public long ttl(String token) {
        try{
            Jedis jedis = jedisPool.getResource();
            return jedis.ttl(token);
        }catch(Exception e){
            e.printStackTrace();
        }
        return (long) -2;
    }
}

中转站

设置过期时间30分钟

Redis缓存简单示例_第3张图片

jsp页面接受两个值,key值和value值,jsp就不发了

以下是效果图

Redis缓存简单示例_第4张图片

 

翻车

 

Redis缓存简单示例_第5张图片

原因是:我没打开redis

开启就好了

 

Redis缓存简单示例_第6张图片

 

你可能感兴趣的:(java)