第二十三章、整合Redis实战(SpringBoot2.x)

使用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相关依赖引入

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

        3、相关配置文件配置

#=========redis基础配置=========
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
# 连接超时时间 单位 ms(毫秒)
spring.redis.timeout=3000
#=========redis线程池设置=========
# 连接池中的最大空闲连接,默认值也是8
spring.redis.jedis.pool.max-idle=200
#连接池中的最小空闲连接,默认值也是0
spring.redis.jedis.pool.min-idle=200
# 如果赋值为-1,则表示不限制;pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
spring.redis.jedis.pool.max-active=2000
# 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时
spring.redis.jedis.pool.max-wait=1000

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

注入模板
@Autowired
private StirngRedisTemplate strTplRedis

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

         测试代码如下:

package net.xdclass.base_project.controller;

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;

import net.xdclass.base_project.domain.JsonData;

@RestController
@RequestMapping("/api/v1/redis")
public class RedisController {
	
	@Autowired
	private StringRedisTemplate redisTpl;//redis模版
	
	@GetMapping("/add")
	public Object add(){
		redisTpl.opsForValue().set("name", "xdclass2020");
		return JsonData.buildSuccess("ok");
	}
	
	@GetMapping("/get")
	public Object get(){
		String value = redisTpl.opsForValue().get("name");
		return JsonData.buildSuccess(value);
	}
}

启动springboot,浏览器访问

再次访问如下:

-----------------------------------------------------------------------------------------

将redis封装为工具类使用,测试代码如下:

测试使用的工具类,将JSON字符串转为对象以及将对象转为JSON字符串

package net.xdclass.base_project.utils;

import java.io.IOException;

import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {

    private static ObjectMapper objectMapper = new ObjectMapper();
    
    //对象转字符串
    public static <T> String obj2String(T obj){
        if (obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    //字符串转对象
    public static <T> T string2Obj(String str,Class<T> clazz){
        if (StringUtils.isEmpty(str) || clazz == null){
            return null;
        }
        try {
            return clazz.equals(String.class)? (T) str :objectMapper.readValue(str,clazz);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Redis工具类

package net.xdclass.base_project.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 功能描述:redis工具类
 * @author wq
 *
 */
@Component
public class RedisClient {
	
	@Autowired
	private StringRedisTemplate redisTpl;//redis模版
	
	/**
	 * 功能描述:设置key-value到redis中
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean set(String key, String value){
		try{
			redisTpl.opsForValue().set(key, value);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 功能描述:通过key-获取缓存里面的值
	 * @param key
	 * @return
	 */
	public String get(String key){
		return redisTpl.opsForValue().get(key);
	}
	
}

控制器部分代码如下:

	@Autowired
	private RedisClient redis;
	
	//字符串
	@GetMapping("/add1")
	public Object add1(){
		redis.set("username", "xdclass999");
		return JsonData.buildSuccess("ok");
	} 
	
	@GetMapping("/get1")
	public Object get1(){
		String value = redis.get("username");
		return JsonData.buildSuccess(value);
	}
	
	//对象
	@GetMapping("/save_user")
	public Object saveUser(){
		User user = new User(1, "tom", "1354255", 33, new Date());
		String userStr = JsonUtils.obj2String(user);
		System.out.println(userStr);
		boolean flag = redis.set("base:user:11", userStr);
		return JsonData.buildSuccess(flag);
	} 
	
	@GetMapping("/find_user")
	public Object findUser(){
		String userStr = redis.get("base:user:11");
		User user = JsonUtils.string2Obj(userStr, User.class);
		return JsonData.buildSuccess(user);
	}

字符串访问测试

对象测试

------------------------------------------------------

还可以在测试文件夹下写测试代码

package base_project.base;

import java.util.Date;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import net.xdclass.base_project.XdclassApplication;
import net.xdclass.base_project.domain.User;
import net.xdclass.base_project.utils.JsonUtils;
import net.xdclass.base_project.utils.RedisClient;

@RunWith(SpringRunner.class) // 底层junit
@SpringBootTest(classes={XdclassApplication.class})//启动springboot工程
public class JsonTest {
	
	@Autowired
	private StringRedisTemplate strTpl;
	
	@Autowired
	private RedisClient redis;
	
	@Test
	public void testOne(){
		User user = new User();
		user.setAge(11);
		user.setCreateTime(new Date());
		user.setName("dandan");
		user.setPhone("1001111");
		String str = JsonUtils.obj2String(user);
		strTpl.opsForValue().set("str", str);
		System.out.println(str);
	}
	
	@Test
	public void testTwo(){
		String str = redis.get("str");
		User user = JsonUtils.string2Obj(str, User.class);
		System.out.println(user);
	}
	
}

以上就是springboot和redis的整合

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荒--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值