First, the use of the cache
The access operation is consistent with the integrated spring, only the expiration time of the key is added.
1. Create a Cachedmanager package access method
Java code
- @Repository
- public class Cachedmanager extends basedao{
- public boolean setcached (String key,object value,long expire) {
- try{
- Super.redisTemplate.opsForValue (). Set (key, value, expire, timeunit.minutes);
- return true;
- }catch (Exception e) {
- Logger.info ("Add cache failed: {}", E.getmessage ());
- return false;
- }
- }
- Public Object getcached (String key) {
- try{
- Return Super.redisTemplate.opsForValue (). get (key);
- }catch (Exception e) {
- Logger.info ("Get Cache failed: {}", E.getmessage ());
- return false;
- }
- }
Add cache time Two more parameters one is the cache time, one is the unit (nanosecond to day optional, source can be seen)
2. Test cache a key for one minute
Java code
- Cached.setcached ("Cached_test", "Hello----", long.valueof (1));
- for (int i = 0; i < i++) {
- Logger.info ("Get Cached data: {}, Current time: {}", cached.getcached ("Cached_test"),
- New SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss")
- . Format (New Date ()));
- Thread.CurrentThread (). Sleep (5000);
- }
The results are visible and expire after one minute. See Cc-redis-tow package:cached and test classes
Ii. comparison with memcached
1. Basic parameters
memcached default port 11211 cache default Expiration Time 30 days (one term is permanent, but can not be saved after 30 days) the value stored in a key is up to 1M, and more than 1M can be split into multiple keys for operation
Redis default port 6379 cache default expiration time does not expire (if default persistence is canceled, data is not persisted to disk, Redis uses the LRU mechanism to erase the most recently used key when memory is exceeded, and writes new data) the value stored in a key is the most 1g bytes of data
2. Storage type
Memcached is similar to a huge hashtable
Redis storage type diverse, bottom-saving byte array
3. Persistence of data
memcached save data in memory, after exceeding, clear invalid key, LRU mechanism to clear the least recently used key
Redis storage data can be persisted to disk in memory and can continue to load using after reboot
get ""
Redis cache usage, differences with memcached