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; }
}
參考博客: