directory

 

1. Introduce dependencies first

2. Add application.properties configuration information

3. Write redis injection SpringBoot configuration class

4. Write tool classes for Redis operations

5. Write test classes

6. Start the class

7. Test

8. Log:


1. Introduce dependencies first

	<! -- redis uses -->
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
Copy the code

 

2. Add application.properties configuration information


# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Redis configuration = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# REDIS (RedisProperties)
# Redis database index (default 0)
spring.redis.database=0  
# Redis server address
spring.redis.host=127.0. 01.
# Redis server connection port
spring.redis.port=6379  
# Redis server connection password (default null)
spring.redis.password=
# maximum number of connections in the pool (use negative values to indicate no limit)
spring.redis.pool.max-active=8  
Maximum connection pool blocking wait time (negative value indicates no limit)
spring.redis.pool.max-wait=-1  
The maximum number of free connections in the connection pool
spring.redis.pool.max-idle=8  
Minimum free connection in connection pool
spring.redis.pool.min-idle=0  
Connection timeout (ms)
spring.redis.timeout=0


# = = = = = = = = = = = = = = = = = = = = = = = = = = Redis configuration = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Copy the code

 

3. Write redis injection SpringBoot configuration class


import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
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.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/** * reids configuration class **@author yushen
 *
 */
@Configuration
@EnableCaching
public class RedisCacheConfig {
	@Bean
	public CacheManager cacheManager(RedisTemplate
        redisTemplate) {
		CacheManager cacheManager = new RedisCacheManager(redisTemplate);
		return cacheManager;
	}

	@Bean
	public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
		RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
		redisTemplate.setConnectionFactory(factory);
		// Key serialization; (otherwise garbled;) , but if the method has a non-string type such as Long, a conversion error will be reported.
		// The ObjectRedisSerializer can be configured without your own key generation policy
		/ / or JdkSerializationRedisSerializer serialization way;
		RedisSerializer<String> redisSerializer = new StringRedisSerializer();// The Long type should not have an exception message;
		redisTemplate.setKeySerializer(redisSerializer);
		redisTemplate.setHashKeySerializer(redisSerializer);
		returnredisTemplate; }}Copy the code

 

4. Write tool classes for Redis operations



import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/** * redi cache tools ** /
@SuppressWarnings("unchecked")
@Component
public class RedisUtil {

	@SuppressWarnings("rawtypes")
	@Autowired
	private RedisTemplate redisTemplate;

	/** * specifies the cache expiration time **@paramThe key key *@paramTime Time (seconds) *@return* /
	public boolean expire(String key, long time) {
		try {
			if (time > 0) {
				redisTemplate.expire(key, time, TimeUnit.SECONDS);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false; }}/** * Obtain expiration time by key **@paramThe key key cannot be NULL *@returnTime (s) returns 0 for permanently valid */
	public long getExpire(String key) {
		return redisTemplate.getExpire(key, TimeUnit.SECONDS);
	}

	/** * Check whether key exists **@paramThe key key *@returnTrue Exists false Does not exist */
	public boolean hasKey(String key) {
		try {
			return redisTemplate.hasKey(key);
		} catch (Exception e) {
			e.printStackTrace();
			return false; }}/** * delete cache **@paramKey can pass one value or more */
	public void del(String... key) {
		if(key ! =null && key.length > 0) {
			if (key.length == 1) {
				redisTemplate.delete(key[0]);
			} else{ redisTemplate.delete(CollectionUtils.arrayToList(key)); }}}// ============================String=============================

	/** * Ordinary cache fetch **@paramThe key key *@returnValue * /
	public Object get(String key) {
		return key == null ? null : redisTemplate.opsForValue().get(key);
	}

	/** * Normal cache into **@paramThe key key *@paramThe value value *@returnTrue Successful false failed */
	public boolean set(String key, Object value) {
		try {
			redisTemplate.opsForValue().set(key, value);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false; }}/** * Normal cache is placed and set time **@paramThe key key *@paramThe value value *@paramTime Time (s) Time must be greater than 0. If time is less than or equal to 0, the value is set indefinitely *@returnTrue Successful false failed */
	public boolean set(String key, Object value, long time) {
		try {
			if (time > 0) {
				redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
			} else {
				set(key, value);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false; }}/** * increment **@paramThe key key *@paramBy is going to be increased by how much (greater than 0) star@return* /
	public long incr(String key, long delta) {
		if (delta < 0) {
			throw new RuntimeException("The increasing factor must be greater than zero.");
		}
		return redisTemplate.opsForValue().increment(key, delta);
	}

	/** * decrements **@paramThe key key *@paramBy is going to be reduced by a few times@return* /
	public long decr(String key, long delta) {
		if (delta < 0) {
			throw new RuntimeException("The decrement factor must be greater than zero.");
		}
		return redisTemplate.opsForValue().increment(key, -delta);
	}

	// ================================Map=================================

	/**
	 * HashGet
	 *
	 * @paramThe key key cannot be NULL *@paramItem items cannot be null *@returnValue * /
	public Object hget(String key, String item) {
		return redisTemplate.opsForHash().get(key, item);
	}

	/** * get all keys ** corresponding to the hashKey@paramThe key key *@returnCorresponding multiple key values */
	public Map<Object, Object> hmget(String key) {
		return redisTemplate.opsForHash().entries(key);
	}

	/**
	 * HashSet
	 *
	 * @paramThe key key *@paramMap corresponds to multiple key values *@returnTrue Successful false failed */
	public boolean hmset(String key, Map<String, Object> map) {
		try {
			redisTemplate.opsForHash().putAll(key, map);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false; }}/** * HashSet and set the time **@paramThe key key *@paramMap corresponds to multiple key values *@paramTime Time (seconds) *@returnTrue Successful false failed */
	public boolean hmset(String key, Map<String, Object> map, long time) {
		try {
			redisTemplate.opsForHash().putAll(key, map);
			if (time > 0) {
				expire(key, time);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false; }}/** * puts data into a hash table, or creates ** if none exists@paramThe key key *@paramItem item *@paramThe value value *@returnTrue Successful false failed */
	public boolean hset(String key, String item, Object value) {
		try {
			redisTemplate.opsForHash().put(key, item, value);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false; }}/** * puts data into a hash table, or creates ** if none exists@paramThe key key *@paramItem item *@paramThe value value *@paramTime Time (s) Note: If the existing hash table has time, the original time * will be replaced@returnTrue Successful false failed */
	public boolean hset(String key, String item, Object value, long time) {
		try {
			redisTemplate.opsForHash().put(key, item, value);
			if (time > 0) {
				expire(key, time);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false; }}/** * Delete the value ** from the hash table@paramThe key key cannot be NULL *@paramItem items can be more than null */
	public void hdel(String key, Object... item) {
		redisTemplate.opsForHash().delete(key, item);
	}

	/** * Determines whether the item value ** exists in the hash table@paramThe key key cannot be NULL *@paramItem items cannot be null *@returnTrue Exists false Does not exist */
	public boolean hHasKey(String key, String item) {
		return redisTemplate.opsForHash().hasKey(key, item);
	}

	/** * hash increments that do not exist create one and return the new value **@paramThe key key *@paramItem item *@paramBy is going to be increased by how much (greater than 0) star@return* /
	public double hincr(String key, String item, double by) {
		return redisTemplate.opsForHash().increment(key, item, by);
	}

	/** * hash decrement **@paramThe key key *@paramItem item *@paramI'm going to subtract by (less than 0) star@return* /
	public double hdecr(String key, String item, double by) {
		return redisTemplate.opsForHash().increment(key, item, -by);
	}

	// ============================set=============================

	/** * Get all values in Set based on key **@paramThe key key *@return* /
	public Set<Object> sGet(String key) {
		try {
			return redisTemplate.opsForSet().members(key);
		} catch (Exception e) {
			e.printStackTrace();
			return null; }}/** * select * from a set based on value@paramThe key key *@paramThe value value *@returnTrue Exists false Does not exist */
	public boolean sHasKey(String key, Object value) {
		try {
			return redisTemplate.opsForSet().isMember(key, value);
		} catch (Exception e) {
			e.printStackTrace();
			return false; }}/** * Put the data into the set cache **@paramThe key key *@paramValues can be multiple *@returnNumber of successes */
	public long sSet(String key, Object... values) {
		try {
			return redisTemplate.opsForSet().add(key, values);
		} catch (Exception e) {
			e.printStackTrace();
			return 0; }}/** * Put set data into cache **@paramThe key key *@paramTime Time (seconds) *@paramValues can be multiple *@returnNumber of successes */
	public long sSetAndTime(String key, long time, Object... values) {
		try {
			Long count = redisTemplate.opsForSet().add(key, values);
			if (time > 0)
				expire(key, time);
			return count;
		} catch (Exception e) {
			e.printStackTrace();
			return 0; }}/** * Get the length of the set cache **@paramThe key key *@return* /
	public long sGetSetSize(String key) {
		try {
			return redisTemplate.opsForSet().size(key);
		} catch (Exception e) {
			e.printStackTrace();
			return 0; }}/** * removes ** of value@paramThe key key *@paramValues can be multiple *@returnNumber of removals */
	public long setRemove(String key, Object... values) {
		try {
			Long count = redisTemplate.opsForSet().remove(key, values);
			return count;
		} catch (Exception e) {
			e.printStackTrace();
			return 0; }}// ===============================list=================================

	/** * retrieve the contents of the list cache **@paramThe key key *@paramStart to *@paramEnd End 0 to -1 represent all values *@return* /
	public List<Object> lGet(String key, long start, long end) {
		try {
			return redisTemplate.opsForList().range(key, start, end);
		} catch (Exception e) {
			e.printStackTrace();
			return null; }}/** * Get the length of the list cache **@paramThe key key *@return* /
	public long lGetListSize(String key) {
		try {
			return redisTemplate.opsForList().size(key);
		} catch (Exception e) {
			e.printStackTrace();
			return 0; }}/** * Get the value ** from the list by index@paramThe key key *@paramIndex index>=0, 0, 1, second element, and so on; When index<0, -1, the end of the table, the next-to-last element of -2, and so on@return* /
	public Object lGetIndex(String key, long index) {
		try {
			return redisTemplate.opsForList().index(key, index);
		} catch (Exception e) {
			e.printStackTrace();
			return null; }}/** * Put the list in the cache **@paramThe key key *@paramThe value value *@paramTime Time (seconds) *@return* /
	public boolean lSet(String key, Object value) {
		try {
			redisTemplate.opsForList().rightPush(key, value);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false; }}/** * Put the list in the cache **@paramThe key key *@paramThe value value *@paramTime Time (seconds) *@return* /
	public boolean lSet(String key, Object value, long time) {
		try {
			redisTemplate.opsForList().rightPush(key, value);
			if (time > 0)
				expire(key, time);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false; }}/** * Put the list in the cache **@paramThe key key *@paramThe value value *@paramTime Time (seconds) *@return* /
	public boolean lSet(String key, List<Object> value) {
		try {
			redisTemplate.opsForList().rightPushAll(key, value);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false; }}/** * Put the list in the cache **@paramThe key key *@paramThe value value *@paramTime Time (seconds) *@return* /
	public boolean lSet(String key, List<Object> value, long time) {
		try {
			redisTemplate.opsForList().rightPushAll(key, value);
			if (time > 0)
				expire(key, time);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false; }}/** * Modify a list of data ** based on the index@paramThe key key *@paramThe index index *@paramThe value value *@return* /
	public boolean lUpdateIndex(String key, long index, Object value) {
		try {
			redisTemplate.opsForList().set(key, index, value);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false; }}/** * remove N values to value **@paramThe key key *@paramCount removes how many *@paramThe value value *@returnNumber of removals */
	public long lRemove(String key, long count, Object value) {
		try {
			Long remove = redisTemplate.opsForList().remove(key, count, value);
			return remove;
		} catch (Exception e) {
			e.printStackTrace();
			return 0; }}}Copy the code

 

5. Write test classes


import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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;

/** * Redis test class **@author yushen
 *
 */
@Controller
@RequestMapping("/RedisController")
public class RedisController {

	@Autowired
	private RedisUtil redisutil;

	private final static Log logger = LogFactory.getLog(RedisController.class);

	/** * add method STR **@param request
	 */
	@RequestMapping("/setStr")
	@ResponseBody
	public int setStr(HttpServletRequest request) {
		String key = request.getParameter("k");
		String value = request.getParameter("v");
		redisutil.set(key, value);
		logger.info(key + ":" + value);
		return 1;
	}

	/** * display method STR **@param request
	 * @return* /
	@RequestMapping("/getStr")
	@ResponseBody
	public String getStr(HttpServletRequest request) {
		String key = request.getParameter("k");
		String value = redisutil.get(key).toString();
		logger.info(key + ":" + value);
		returnvalue; }}Copy the code

 

6. Start the class



import org.apache.log4j.BasicConfigurator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

import com.supermap.filter.ServletLoginFilter;
import com.supermap.filter.ServletSecurityFilter;

/** * Project startup class **@author yushen
 *
 */
@SpringBootApplication
public class PorjectStart {

	/** * Project startup entry **@param args
	 */
	public static void main(String[] args) { SpringApplication.run(PorjectStart .class, args); }}Copy the code

 

7. Test

Type in the browser

http://localhost:8080/RedisController/setStr?k=s5&v=saaaaaaaaaaaaaa

http://localhost:8080/RedisController/getStr?k=s5

 

8. Log:

2018-12-27 15:37:38.579 INFO  com.supermap.redis.RedisController - s5:saaaaaaaaaaaaaa
2018-12-27 15:37:57.823 INFO  com.supermap.redis.RedisController - s5:saaaaaaaaaaaaaa
Copy the code

 

That’s it!

 

From: blog.csdn.net/weixin_4274…