SpringBoot2.x整合redis实战讲解

SpringBoot2.x整合redis实战讲解

    简介:使用springboot-starter整合reids实战

        1、官网:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-redis
            集群文档:https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#cluster

        2、springboot整合redis相关依赖引入
            
                org.springframework.boot
                spring-boot-starter-data-redis
            

        
        3、相关配置文件配置
            #=========redis基础配置=========
            spring.redis.database=0
            spring.redis.host=127.0.0.1
            spring.redis.port=6390
            # 连接超时时间 单位 ms(毫秒)
            spring.redis.timeout=3000

            #=========redis线程池设置=========
            # 连接池中的最大空闲连接,默认值也是8。
            spring.redis.pool.max-idle=200

            #连接池中的最小空闲连接,默认值也是0。
            spring.redis.pool.min-idle=200
            
            # 如果赋值为-1,则表示不限制;pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
            spring.redis.pool.max-active=2000

            # 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时
            spring.redis.pool.max-wait=1000

        4、常见redistemplate种类讲解和缓存实操(使用自动注入)

            1、注入模板
            @Autowired
            private StirngRedisTemplate strTplRedis

            2、类型String,List,Hash,Set,ZSet
            对应的方法分别是opsForValue()、opsForList()、opsForHash()、opsForSet()、opsForZSet()

package net.leon.base_project.controller;

import net.leon.base_project.domain.JsonData;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/api/v1/redis")
public class RdisTestController {

	
	@Autowired
	private StringRedisTemplate redisTpl; //jdbcTemplate

	@GetMapping(value="add")
	public Object add(){
		
		//opsForValue : Returns the operations performed on simple values (or Strings in Redis terminology).
 
		redisTpl.opsForValue().set("name", "leon2018");
		
		return JsonData.buildSuccess();
		
	}
	
	@GetMapping(value="get")
	public Object get(){
		
		String value = redisTpl.opsForValue().get("name");		
		return JsonData.buildSuccess(value);
		
	}	
}

Redis

Redis is a cache, message broker, and richly-featured key-value store. Spring Boot offers basic auto-configuration for the Lettuce and Jedis client libraries and the abstractions on top of them provided by Spring Data Redis.

There is a spring-boot-starter-data-redis “Starter” for collecting the dependencies in a convenient way. By default, it uses Lettuce. That starter handles both traditional and reactive applications.

[Tip]

we also provide a spring-boot-starter-data-redis-reactive “Starter” for consistency with the other stores with reactive support.

Connecting to Redis

You can inject an auto-configured RedisConnectionFactoryStringRedisTemplate, or vanilla RedisTemplate instance as you would any other Spring Bean. By default, the instance tries to connect to a Redis server at localhost:6379. The following listing shows an example of such a bean:

@Component
public class MyBean {

	private StringRedisTemplate template;

	@Autowired
	public MyBean(StringRedisTemplate template) {
		this.template = template;
	}

	// ...

}
[Tip]

You can also register an arbitrary number of beans that implement LettuceClientConfigurationBuilderCustomizer for more advanced customizations. If you use Jedis, JedisClientConfigurationBuilderCustomizer is also available.

If you add your own @Bean of any of the auto-configured types, it replaces the default (except in the case of RedisTemplate, when the exclusion is based on the bean name, redisTemplate, not its type). By default, if commons-pool2 is on the classpath, you get a pooled connection factory.

Maven configuration

Add the Maven dependency:


  org.springframework.data
  spring-data-redis
  ${version}.RELEASE

If you’d rather like the latest snapshots of the upcoming major version, use our Maven snapshot repository and declare the appropriate dependency version.

package net.leon.base_project.domain;

import java.io.Serializable;

/**
 * 功能描述:响应结果类
 */
public class JsonData implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Integer code; // 状态码 0 表示成功,1表示处理中,-1表示失败
	private Object data; // 数据
	private String msg;// 描述

	public JsonData() {
	}

	public JsonData(Integer code, Object data, String msg) {
		this.code = code;
		this.data = data;
		this.msg = msg;
	}

	// 成功,传入数据
	public static JsonData buildSuccess() {
		return new JsonData(0, null, null);
	}

	// 成功,传入数据
	public static JsonData buildSuccess(Object data) {
		return new JsonData(0, data, null);
	}

	// 失败,传入描述信息
	public static JsonData buildError(String msg) {
		return new JsonData(-1, null, msg);
	}

	// 失败,传入描述信息,状态码
	public static JsonData buildError(String msg, Integer code) {
		return new JsonData(code, null, msg);
	}

	// 成功,传入数据,及描述信息
	public static JsonData buildSuccess(Object data, String msg) {
		return new JsonData(0, data, msg);
	}

	// 成功,传入数据,及状态码
	public static JsonData buildSuccess(Object data, int code) {
		return new JsonData(code, data, null);
	}

	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	@Override
	public String toString() {
		return "JsonData [code=" + code + ", data=" + data + ", msg=" + msg
				+ "]";
	}

}

 

你可能感兴趣的:(SpringBoot2.x整合redis实战讲解)