Springboot Integrated Redis Detailed

Source: Internet
Author: User
Tags delete key propertyaccessor

Welcome to join Java Kochi Group Communication


Springboot Integrated Redis is simple

1. Introducing MAVEN-dependent Redis packages

<!--  Springboot integrated Redis--><dependency>    <groupid>org.springframework.boot</groupid >    <artifactId>spring-boot-starter-redis</artifactId></dependency>


2. Configuring the Redis environment in the APPLICATION.YML configuration file

Spring:  redis:    host:localhost    #password: Redispassword    port:6379    pool:      max-idle:100      min-idle:1      max-active:1000      max-wait:-1


3. Writing configuration file Redisconfig

Package Com.kinder.redis;import Java.lang.reflect.method;import Org.springframework.cache.cachemanager;import Org.springframework.cache.annotation.cachingconfigurersupport;import Org.springframework.cache.annotation.enablecaching;import Org.springframework.cache.interceptor.KeyGenerator; Import Org.springframework.context.annotation.bean;import org.springframework.context.annotation.Configuration; Import Org.springframework.data.redis.cache.rediscachemanager;import Org.springframework.data.redis.connection.redisconnectionfactory;import Org.springframework.data.redis.core.redistemplate;import Org.springframework.data.redis.core.stringredistemplate;import Org.springframework.data.redis.serializer.jackson2jsonredisserializer;import Com.fasterxml.jackson.annotation.jsonautodetect;import Com.fasterxml.jackson.annotation.propertyaccessor;import Com.fasterxml.jackson.databind.ObjectMapper, @Configuration @enablecachingpublic class Redisconfig extends Cachingconfigurersupport {/** * strategy to generate key * *@return */@Beanpublic keygenerator Keygenerator () {return new Keygenerator () {@Overridepublic object Generate (Object Target, method, Object ... params) {StringBuilder sb = new StringBuilder (); Sb.append (Target.getclass (). GetName ()) ; Sb.append (Method.getname ()); for (Object obj:params) {sb.append (obj.tostring ());} return sb.tostring ();}};} /** * Manage Cache */@Beanpublic CacheManager CacheManager (redistemplate redistemplate) {Rediscachemanager RCM = new Rediscachema Nager (redistemplate); return RCM;} /** * redistemplate configuration */@Beanpublic redistemplate<string, string> redistemplate (Redisconnectionfactory Factory) {stringredistemplate template = new Stringredistemplate (factory); Jackson2jsonredisserializer Jackson2jsonredisserializer = new Jackson2jsonredisserializer (Object.class); O Bjectmapper om = new Objectmapper (); Om.setvisibility (Propertyaccessor.all, JsonAutoDetect.Visibility.ANY); o M.enabledefaulttyping (ObjectMapper.DefaultTyping.NON_FINAL); Jackson2jsonredisserializer.setobjectmapper (OM); Template.setvalueserializer (Jackson2jsonredisserializer); Template.afterpropertiesset (); return template;}} 


4. Service class to write Redis services

Package Com.kinder.redis;import Java.io.serializable;import Java.util.list;import java.util.set;import Java.util.concurrent.timeunit;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.data.redis.core.setoperations;import org.springframework.data.redis.core.ValueOperations; Import Org.springframework.data.redis.core.zsetoperations;import org.springframework.stereotype.service;@ Servicepublic class Redisservice {@Autowiredprivate redistemplate redistemplate;/** * Write Cache * @param key * @param value * @return */public Boolean set (Final String key, Object value) {Boolean result = False;try {valueoperations<serializabl E, object> operations = Redistemplate.opsforvalue (); Operations.set (key, value); result = true;} catch (Exception e) {e.printstacktrace ();} return result;} /** * Write Cache settingsAging Time * * @param key * @param value * @return */public Boolean set (Final String key, Object value, Long expiretime) {Boole An result = False;try {valueoperations<serializable, object> operations = Redistemplate.opsforvalue (); O Perations.set (key, value); Redistemplate.expire (Key, Expiretime, timeunit.seconds); result = true;} catch (Exception e) {e.printstacktrace ();} return result;} /** * Bulk Delete the corresponding value * * @param keys */public void Remove (final String ... keys) {for (string Key:keys) {remove (key);}} /** * Bulk Delete key * * @param pattern */public void Removepattern (final String pattern) {set<serializable> keys = RedisT Emplate.keys (pattern); if (keys.size () > 0) redistemplate.delete (keys); /** * Delete the corresponding value * * @param key */public void Remove (final String key) {if (Exists (key)) {Redistemplate.delete (key);}} /** * Determine if there is a corresponding value in the cache * * @param key * @return */public Boolean exists (final String key) {return Redistemplate.haskey (ke y);} /** * Read Cache * * @param key * @return */public Object geT (final String key) {valueoperations<serializable, object> operations = Redistemplate.opsforvalue (); return Operations.get (key);} /** * Hash Add * * @param key * @param hashkey * @param value */public void Hmset (String key, Object HashKey, Object value) {hashoperations<string, Object, object> hash = Redistemplate.opsforhash (); Hash.put (key, HashKey, value);} /** * Hash Fetch data * * @param key * @param hashkey * @return */public object Hmget (String key, Object HashKey) {hashoperations& Lt String, Object, object> hash = Redistemplate.opsforhash (); return Hash.get (Key, HashKey);} /** * List Add * * @param k * @param v */public void Lpush (String K, Object v) {listoperations<string, object> list = R Edistemplate.opsforlist (); List.rightpush (k, v);} /** * List Get * * @param k * @param l * @param L1 * @return */public list<object> lrange (String K, long L, long L1) {L istoperations<string, object> list = Redistemplate.opsforlist (); return List.range (K, L, L1);} /** * Collection Add * * @param keY * @param value */public void Add (String key, Object value) {setoperations<string, object> set = REDISTEMPLATE.OPSF Orset (); Set.add (key, value);} /** * Collection Gets * * @param key * @return */public set<object> setmembers (String key) {setoperations<string, Object&gt ; Set = Redistemplate.opsforset (); return set.members (key);} /** * Ordered Collection Add * * @param key * @param value * @param scoure */public void Zadd (String key, Object value, double scoure) {Z setoperations<string, object> zset = Redistemplate.opsforzset (); Zset.add (key, value, scoure);} /** * Ordered Collection gets * * @param key * @param scoure * @param scoure1 * @return */public set<object> rangebyscore (String key , double scoure, double scoure1) {zsetoperations<string, object> zset = Redistemplate.opsforzset (); return Zset.rangebyscore (Key, Scoure, Scoure1);}}


5. Operation of Redis.

Package Com.kinder.demo.controller;import Java.util.hashmap;import Java.util.map;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.responsebody;import Com.kinder.redis.redisservice;import com.kinder.util.resultutil;/** * Redis Operation * * @author Administrator * */@Controller @requestmapping ("/demo/redis") public Class Rediscontroller {@Autowiredprivate redisservice redisservice;/** * Redis Data set * * @param key * @param value * @retur n */@RequestMapping ("/setredis.do") @ResponseBodypublic Object Setredis (string key, String value) {Redisservice.set ( Key, value); return resultutil.returnsuccess ();}  /** * Delete Redis data according to key * * @param key * @return */@RequestMapping ("/delredis.do") @ResponseBodypublic Object Delredis (String Key) {Redisservice.remove (key); return resultutil.returnsuccess ();} /** * Get Redis data based on key * * @param key * @return */@RequestMapping ("/getredis.do") @ResponseBodypublic object Getredis (String key) {Object value = Redisservice.get (key) ; map<string, object> map = new hashmap<string, object> (); Map.put ("value", value); return Resultutil.returnsuccess (map);}}


The end.

Welcome to join Java Kochi Group communication


Springboot Integrated Redis Detailed

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.