redis在Web中的使用

redis是一个键值对数据库,用于缓存数据。

redis是一个key-value存储系统。和Memcached数据库类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。

在javaWeb中使用Redis有几种方法:

1.使用Jedis。Jedis是Redis官方推荐的面向Java的操作Redis的客户端;

2.使用RedisTemplate 。RedisTemplate是SpringDataRedis中对JedisApi的高度封装。
SpringDataRedis相对于Jedis来说可以方便地更换Redis的Java客户端,比Jedis多了自动管理连接池的特性,方便与其他Spring框架进行搭配使用。

3.使用其他人封装好的开源的工具类RedisUti

在web中获取key对应的value值的方法如下:

RedisTemplate  redisTemplate=new RedisTemplate ();
ValueOperations<String, City> operations = redisTemplate.opsForValue();
boolean hasKey = redisTemplate.hasKey(key);
if(hasKey) {
   City city= operations.get(key);
}

 设置key和value如下:

RedisTemplate  redisTemplate=new RedisTemplate ();
ValueOperations<String, City> operations = redisTemplate.opsForValue();

operations.set(key, city)

另外,需要操作字符串时,可以用StringRedisTemplate代替RedisTemplate,通过opsForValue()方法进行增删改查。

代码示例如下:

@Service
public class CityServiceImpl implements CityService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CityServiceImpl.class);

    @Autowired
    private CityDao cityDao;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取城市逻辑:
     * 如果缓存存在,从缓存中获取城市信息
     * 如果缓存不存在,从 DB 中获取城市信息,然后插入缓存
     */
    @Override
    public City findCityById(Long id) {
        // 从缓存中获取城市信息
        String key = "city_" + id;
        ValueOperations<String, City> operations = redisTemplate.opsForValue();

        // 缓存存在
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            City city = operations.get(key);

            LOGGER.info("CityServiceImpl.findCityById() : 从缓存中获取了城市 >> " + city.toString());
            return city;
        }

        // 从 DB 中获取城市信息
        City city = cityDao.findById(id);

        // 插入缓存
        operations.set(key, city, 10, TimeUnit.SECONDS);
        LOGGER.info("CityServiceImpl.findCityById() : 城市插入缓存 >> " + city.toString());

        return city;
    }
}

参考博客:

https://www.jianshu.com/p/7bf5dc61ca06

原文地址:https://www.cnblogs.com/expiator/p/8274673.html