Used in the company's projects Redis, I've been learning about this recently . From the beginning to the present , The general feeling for me is Redis It's easier to get started , But mastery requires a lot of practice and research . Fortunately, our company is right Redis Its use is not so deep , At present, only some simple operations can be carried out . Summarize the learning results of these days , Write it down , Hope helps consolidate and improve .

  explain : my Redis Service is built on virtual machine Linux(Read
Heat6.2) On system ,Mysql Database is installed on this machine , The network connection mode of virtual machine is bridging , Share a network segment with this computer . There are many examples of building on the Internet , I won't explain it here .

  First of all SpringBoot Profile in (application.yml Profile of type , This type of document has strict requirements for writing format )


server: port: 8090 spring: datasource: url:
jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true
username:xxx password: xxx driver-class-name: com.mysql.jdbc.Driver
test-on-borrow:false test-while-idel: true time-between-eviction-runs-millis:
3600000tomcat: max-wait: 10000 max-active: 50 http: encoding: force: true
jpa: hibernate: ddl-auto: update max_fetch_depth: 2 naming: physical-strategy:
org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImplproperties:
hibernate: dialect: org.hibernate.dialect.MySQL5Dialect max_fetch_depth: 2
format_sql:true show-sql: true redis: host: xxx password: port: 6379 pool: #
Maximum free connections in connection pool max-idle: 8 min-idle: 0 # Connection pool maximum connections ( Use a negative value to indicate no limit ) max-active: 8 #
Connection pool maximum block wait time ( Use a negative value to indicate no limit ) max-wait: 1 # Connection timeout ( millisecond ) timeout: 60000
  


And then it's right Redis Configuration of data operation class , Provides a way to serialize data .Spring Encapsulated RedisTimplement Object to Redis Operate , The template defaults to JdkSerializationRedisSerializer

Binary serialization of .



import com.fasterxml.jackson.annotation.JsonAutoDetect; import
com.fasterxml.jackson.annotation.PropertyAccessor;import
com.fasterxml.jackson.databind.ObjectMapper;import
org.springframework.beans.factory.annotation.Autowired; import
org.springframework.cache.annotation.CachingConfigurerSupport;import
org.springframework.context.annotation.Bean; import
org.springframework.context.annotation.Configuration; import
org.springframework.data.redis.connection.RedisConnectionFactory;import
org.springframework.data.redis.core.HashOperations;import
org.springframework.data.redis.core.ListOperations;import
org.springframework.data.redis.core.RedisTemplate;import
org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import
org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
// Annotate a configuration class , Surrender spring Administration public class Config extends CachingConfigurerSupport{ /* *
adopt RedisConnectionFactory introduce redis Connection configuration in configuration file * */ @Autowired private
RedisConnectionFactoryfactory; /* * 1. Why serialization here * reason : There is no way to use ordinary connection Java Object direct deposit Redis
, * We need to provide our own solutions - Object serialization , Then deposit redis, * After retrieving serialized content , Convert to java object * */ @Bean public
RedisTemplate<String,Object> redisTemplate(){ RedisTemplate<String,Object>
template =new RedisTemplate<>(); initDomainRedisTemplate(template,factory);
returntemplate; } public void initDomainRedisTemplate(RedisTemplate
template,RedisConnectionFactory factory){
template.setConnectionFactory(factory);// use Jackson2JsonRedisSerializer To serialize and deserialize
redis Of value value Jackson2JsonRedisSerializer<Object> serializer = new
Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper mapper = new
ObjectMapper();//ObjectMapper yes jackson Main categories of , Action serialization
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); //
Set any field visible mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); //
Deserialization serializer.setObjectMapper(mapper);
template.setValueSerializer(serializer); // Set serialization deserialization redis Of value value
template.setKeySerializer(new StringRedisSerializer()); // Set serialization deserialization key The value is
String template.afterPropertiesSet(); // Initialize operation , After setting } // instantiation HashOperations
object , have access to Hash Type operation @Bean public HashOperations<String,String,Object>
hashOperations(RedisTemplate<String,Object> redisTemplate){return
redisTemplate.opsForHash();//opsForHash() This method is used for operation Hash } // instantiation ListOperations
object , have access to List Type operation @Bean public ListOperations<String,Object>
listOperations(RedisTemplate<String,Object> redisTemplate){return
redisTemplate.opsForList();//opsForList() This method is used for operation List } }
And then it's right Redis Tool class for data operation , Three types of data are listed here ,String,Hash,List import
org.springframework.beans.factory.annotation.Autowired; import
org.springframework.data.redis.core.HashOperations;import
org.springframework.data.redis.core.ListOperations;import
org.springframework.data.redis.core.RedisTemplate;import
org.springframework.stereotype.Component; import java.util.List; import
java.util.Map;import java.util.concurrent.TimeUnit; @Component public class
RedisUtil { /* * explain : Personal summary: redisTemplate Can handle redis All data types in . *
But for the processing of specific data types , All kinds of interfaces are easier to handle , * There are many methods * */ @Autowired private
RedisTemplate<String,Object>redisTemplate; @Autowired private
HashOperations<String,String,Object>hashOperations; @Autowired private
ListOperations<String,Object>listOperations;
/*--------------------------------------------- Public area
---------------------------------------------------*/ // judge key Does it exist public
booleanhasKey(String key){ return redisTemplate.hasKey(key); } // according to key delete key and
value public void deleteByKey(String key){ redisTemplate.delete(key); } /* * set up
key Validity of * @param key,time( Effective time ),unit(hours,days,minutes) * */ public void
setExpire(String key,long time,TimeUnit unit){ if (time != -1){ redisTemplate
.expire(key,time,unit); } }/*--------------------------------------------- Public area
---------------------------------------------------*/
/*----------------------------------------------String-------------------------------------------------*/
// according to key obtain value value public String getValue(String key){ return (String)
redisTemplate.opsForValue().get(key); } // insert data public void setValue(String
key,String value){redisTemplate.opsForValue().set(key,value); }
/*----------------------------------------------String------------------------------------------------*/

/*-----------------------------------------------hash--------------------------------------------------*/
// Deposit hash Value of type public void addAllForHash(String key, Map<String,Object> map){
hashOperations.putAll(key,map); } /* * according to key Query this key corresponding map All under value * @param key
* @return List<AllValue> * */ public List<Object> getAllValueForHash(String
key){return hashOperations.values(key); } // obtain Hash Single in value public Object
getValueForHash(String key, String hashKey){return hashOperations
.get(key,hashKey); }// obtain Hash number public Long getCount(String key){ return
hashOperations.size(key); } /* * according to key and hashKey delete value * @param key,hashKey *
@return void * */ public void deleteValueByKeyAndHashKey(String key,String
hashKey){hashOperations.delete(key,hashKey); } /* * Judge current key in hashKey Does it exist *
@param key,hashKey * @return true / false * */ public boolean hasHashKey(String
key,String hashKey){return hashOperations.hasKey(key,hashKey); } /* * query key Next all
Hash value * @param key * @return Map<key,value> * */ public Object
getAllHashByKey(String key){return hashOperations.entries(key); }
/*-----------------------------------------------hash----------------------------------------------------*/

/*-----------------------------------------------list----------------------------------------------------*/
/* * from list Queue tail data * @param key,List * @return null * */ public void
rightPushAll(String key, List<String> values){listOperations
.rightPushAll(key,values); } /* * from list Queue tail data * @param key,value * @return
null * */ public void rightPush(String key, String value){ listOperations
.rightPush(key,value); }/* * from list Get all data in the queue (0,listSize) * @param key * @return
List * */ public List<Object> getListAll(String key){ return listOperations
.range(key,0,listOperations.size(key)); }
/*-----------------------------------------------list---------------------------------------------------*/
}