SpringBoot 2.x (10):整合Redis

Redis部署到阿里云:

下载redis源码,编译,允许远程访问的配置

 

阿里云安全组设置:

 

SSH连过去:

wget http://download.redis.io/releases/redis-4.0.9.tar.gz

tar xzf redis-4.0.9.tar.gz

cd redis-4.0.9

make

 

编译完成后cd到目录

vi redis.conf

bind改成0.0.0.0

protected-mode改成no

daemonize改为no(可选)

 

cd到src目录,运行redis:

./redis-server

也可以用守护进程的方式启动 

 

设置密码:这一步是必须的,防止被人恶意连接

./redis-cli

config set requirepass [your password]

 

如果要关闭redis:

./redis-cli -p 6379 shutdown即可

 

测试是否远程连接成功的方式:采用RedisDesktopManager连接

 

SpringBoot整合Redis:

依赖:

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

 

注意:SpringBoot默认操作Redis使用的是Lettuce而不是Jedis

网上大佬说Lettuce比Jedis性能好,我不了解,不做评论

如果想用Jedis,需要自行配置:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

 

下面是配置文件,其中Redis的配置是必须的,Redis Pool配置可选

Jedis配置文件:

# Redis
spring.redis.database=0
spring.redis.host=[Redis服务器IP]
spring.redis.port=6379
spring.redis.password=[密码]
spring.redis.timeout=3000
# Redis Pool
spring.redis.jedis.pool.max-idle=300
spring.redis.jedis.pool.min-idle=300
spring.redis.jedis.pool.max-active=2000
spring.redis.jedis.pool.max-wait=1000

 

Lettuce配置文件:我使用Lettuce的时候出现了各种BUG,简易还是用稳妥的Jedis吧

# Redis
spring.redis.database=0
spring.redis.host=[Redis服务器IP]
spring.redis.port=6379
spring.redis.password=[密码]
spring.redis.timeout=3000
# Redis Pool
spring.redis.lettuce.pool.max-idle=300
spring.redis.lettuce.pool.min-idle=300
spring.redis.lettuce.pool.max-active=2000
spring.redis.lettuce.pool.max-wait=1000

 

使用Spring的StringRedisTemplate进行简单的操作:

package org.dreamtech.redisdemo.controller;

import java.util.HashMap;
import java.util.Map;

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.RestController;

@RestController
public class RedisTestController {

    @Autowired
    private StringRedisTemplate redisTpl;

    private Map<String, Object> modelMap = new HashMap<String, Object>();

    @GetMapping("/add")
    private Object add(String name) {
        modelMap.clear();
        if (name != null && !name.equals("")) {
            redisTpl.opsForValue().set("name", name);
            modelMap.put("success", true);
        } else {
            modelMap.put("success", false);
        }
        return modelMap;
    }

    @GetMapping("/get")
    private Object get() {
        modelMap.clear();
        String name = redisTpl.opsForValue().get("name");
        modelMap.put("success", true);
        modelMap.put("name", name);
        return modelMap;
    }
}

 

访问:

http://localhost:8080/add?name=xxx   设置name参数

http://localhost:8080/get   获取name参数

如果能够获取到设置的参数,说明整合redis成功

 

Redis工具类的简单封装:对其他数据类型可以自行进行封装,我这里只是最简单的操作封装

package org.dreamtech.redisdemo.util;

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

/**
 * Redis工具类
 * 
 * @author Xu Yiqing
 *
 */
@Component
public class RedisUtil {
    @Autowired
    private StringRedisTemplate redisTpl;

    /**
     * SET操作
     * 
     * @param key   KEY
     * @param value VALUE
     * @return 是否成功
     */
    public boolean set(String key, String value) {
        try {
            redisTpl.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * GET操作
     * 
     * @param key KEY
     * @return VALUE
     */
    public String get(String key) {
        try {
            String value = redisTpl.opsForValue().get(key);
            return value;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

 

如何将对象存入Redis呢?

无法将对象存入Redis!但是可以把对象转为JSON存入Redis

实现:

JSON工具类封装:

package org.dreamtech.redisdemo.util;

import java.io.IOException;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;

@SuppressWarnings("unchecked")
public class JsonUtils {

    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 对象转字符串
     * 
     * @param <T> 泛型
     * @param obj 对象
     * @return 字符串
     */
    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;
        }
    }

    /**
     * 字符串转对象
     * 
     * @param <T>   泛型
     * @param str   字符串
     * @param clazz 对象类型
     * @return 对象
     */
    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;
        }
    }
}

 

实体类:

package org.dreamtech.redisdemo.domain;

public class User {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

 

Controller:

package org.dreamtech.redisdemo.controller;

import java.util.HashMap;
import java.util.Map;

import org.dreamtech.redisdemo.domain.User;
import org.dreamtech.redisdemo.util.JsonUtils;
import org.dreamtech.redisdemo.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisTestController {

    @Autowired
    private RedisUtil redis;

    private Map<String, Object> modelMap = new HashMap<String, Object>();

    @GetMapping("/add")
    private Object add(String name) {
        modelMap.clear();
        boolean flag = redis.set("name", "redis");
        if (flag) {
            modelMap.put("success", true);
        } else {
            modelMap.put("success", false);
        }
        return modelMap;
    }

    @GetMapping("/get")
    private Object get() {
        modelMap.clear();
        String name = redis.get("name");
        modelMap.put("success", true);
        modelMap.put("name", name);
        return modelMap;
    }

    @GetMapping("/setuser")
    private Object setUser() {
        modelMap.clear();
        User user = new User();
        user.setUsername("admin");
        user.setPassword("passsword");
        boolean flag = redis.set("user", JsonUtils.obj2String(user));
        if (flag) {
            modelMap.put("success", true);
        } else {
            modelMap.put("success", false);
        }
        return modelMap;
    }

    @GetMapping("/getuser")
    private Object getUser() {
        modelMap.clear();
        String tempUser = redis.get("user");
        User user = JsonUtils.string2Obj(tempUser, User.class);
        modelMap.put("user", user);
        modelMap.put("success", true);
        return modelMap;
    }
}

 

如果感觉Controller层测试太复杂,可以采用SpringBootTest:

package org.dreamtech.redisdemo;

import org.dreamtech.redisdemo.domain.User;
import org.dreamtech.redisdemo.util.JsonUtils;
import org.dreamtech.redisdemo.util.RedisUtil;
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.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { RedisdemoApplication.class })
public class RedisTest {
    
    @Autowired
    private RedisUtil redis;

    @Test
    public void test() {
        User tempUser = new User();
        tempUser.setUsername("admin");
        tempUser.setPassword("password");
        String user = JsonUtils.obj2String(tempUser);
        redis.set("user", user);
        String result = redis.get("user");
        System.out.println(result);
    }
}

 

posted @ 2019-05-10 13:40  4ra1n  阅读(676)  评论(0编辑  收藏  举报