windows系统本地安装redis步骤
Linux系统各异,我在此不再赘诉
简单介绍下SpringBoot对Jedis的支持吧,在1.×版本的时候,SpringBoot的底层还是使用Jedis来连接Redis的,但是在2.×版本后,就换成了Lettuce。两者的区别如下:=
Jedis: 采用的直连,多个线程操作的话,是不安全的,如果想要避免不安全的,使用 jedis pool 连接池! 更像 BIO 模式!
Lettuce: 采用netty,实例可以再多个线程中进行共享,不存在线程不安全的情况!可以减少线程数据了,更像 NIO 模式!
配置的application.yml文件:4.0.0 org.springframework.boot spring-boot-starter-parent 2.2.4.RELEASE com.dragonZhu springboot-redis 0.0.1-SNAPSHOT springboot-redis Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-data-redis 2.1.7.RELEASE com.alibaba fastjson 1.2.54 compile org.projectlombok lombok 1.18.10 compile org.apache.commons commons-pool2 2.11.1 org.springframework.boot spring-boot-maven-plugin
server:
port: 10001
spring:
redis:
host: 127.0.0.1
port: 6379
password: 123456
# 指定连接的库
database: 0
测试连接
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
public class testRedis {
@Autowired(required = false)
private RedisTemplate redisTemplate;
@Test
void getName(){
redisTemplate.opsForValue().set("name","连接成功!");
System.out.println(redisTemplate.opsForValue().get("name"));
}
}
阶段1完成
import lombok.Data;
@Data
public class User {
private String name;
private Integer age;
private Integer high;
}
测试:
@Test
void setObject(){
User user = new User();
user.setName("UserTest2");
user.setAge(23);
user.setHigh(172);
redisTemplate.opsForValue().set("UserTest2",user);
System.out.println(redisTemplate.opsForValue().get("UserTest2"));
}
出现问题:
结论:所以在操作Redis中,关于对象的保存我们得序列化才可以正常操作! 所以我们自定义RedisTemplate
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
// 这是我给大家写好的一个固定模板,大家在企业中,拿去就可以直接使用!
// 自己定义了一个RedisTemplate
@Bean
@SuppressWarnings("all")
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
// 我们为了自己开发方便,一般直接使用
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(factory);
// Json序列化配置
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// String 的序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
阶段三,使用自定义工具类方便操作
新增工具类
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public final class RedisUtil {
@Resource
private RedisTemplate redisTemplate;
public Set keys(String keys){
try {
return redisTemplate.keys(keys);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
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;
}
}
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete((Collection) CollectionUtils.arrayToList(key));
}
}
}
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean setnx(String key, Object value) {
try {
redisTemplate.opsForValue().setIfAbsent(key,value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
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;
}
}
public boolean setnx(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().setIfAbsent(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
public Map
增加控制层
package com.dragonzhu.springbootredis.Controller;
import com.dragonzhu.springbootredis.Utils.RedisOfDatabaseOneUtil;
import com.dragonzhu.springbootredis.Utils.RedisOfDatabaseTwoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
@Slf4j
@RestController
@RequestMapping("/Redis")
public class RedisController {
@Autowired
private RedisUtil redisUtil ;
@GetMapping("/getName")
public Map getName(@RequestParam Map paramsMap) {
Map resultMap = new HashMap<>();
resultMap.put("name", redisUtil.get(paramsMap.get("name").toString()));
return resultMap;
}
@GetMapping("/setName")
public Object setName(@RequestParam Map paramsMap){
String nameKey = paramsMap.get("nameKey").toString();
String namevalue = paramsMap.get("namevalue").toString();
redisUtil.set(nameKey,namevalue);
return"加入成功!";
}
}
测试
阶段三完成
我们都知道,Redis有很多分库,看看redisDesktop
那么在一个web工程中我们如何操作不同的库呢?
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.ObjectUtils;
import java.time.Duration;
@Configuration
public class RedisDatasourceConfiguration {
@Value("${redis.isCleanRedisCache:false}")
private String cleanRedisCache;
@Value("${redis.host:127.0.0.1}")
public String host;
@Value("${redis.port:6379}")
public Integer port;
private String password;
@Value("${redis.timeout:2000}")
public Integer timeout;
public Integer maxIdle = 16;
public Integer minIdle = 5;
public Integer maxTotal = 30;
@Bean
public RedisTemplate stringRedisTemplate1() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(host, port);
configuration.setDatabase(1);
if (!ObjectUtils.isEmpty(password)) {
RedisPassword redisPassword = RedisPassword.of(password);
configuration.setPassword(redisPassword);
}
return createRedisTemplate(creatFactory(configuration));
}
@Bean
public RedisTemplate stringRedisTemplate2() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(host, port);
configuration.setDatabase(2);
if (!ObjectUtils.isEmpty(password)) {
RedisPassword redisPassword = RedisPassword.of(password);
configuration.setPassword(redisPassword);
}
return createRedisTemplate(creatFactory(configuration));
}
@Bean
public RedisTemplate stringRedisTemplate3() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(host, port);
configuration.setDatabase(3);
if (!ObjectUtils.isEmpty(password)) {
RedisPassword redisPassword = RedisPassword.of(password);
configuration.setPassword(redisPassword);
}
return createRedisTemplate(creatFactory(configuration));
}
@Bean
public RedisTemplate stringRedisTemplate4() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(host, port);
configuration.setDatabase(4);
if (!ObjectUtils.isEmpty(password)) {
RedisPassword redisPassword = RedisPassword.of(password);
configuration.setPassword(redisPassword);
}
return createRedisTemplate(creatFactory(configuration));
}
@Bean
public RedisTemplate stringRedisTemplate5() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(host, port);
configuration.setDatabase(5);
if (!ObjectUtils.isEmpty(password)) {
RedisPassword redisPassword = RedisPassword.of(password);
configuration.setPassword(redisPassword);
}
return createRedisTemplate(creatFactory(configuration));
}
private RedisTemplate getSerializerRedisTemplate(){
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new StringRedisSerializer());
return redisTemplate;
}
private RedisTemplate createRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = getSerializerRedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
private GenericObjectPoolConfig getGenericObjectPoolConfig(){
GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
genericObjectPoolConfig.setMaxTotal(maxTotal);
genericObjectPoolConfig.setMinIdle(minIdle);
genericObjectPoolConfig.setMaxIdle(maxIdle);
genericObjectPoolConfig.setMaxWaitMillis(timeout);
return genericObjectPoolConfig;
}
private LettuceConnectionFactory creatFactory(RedisStandaloneConfiguration configuration){
LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder builder = LettucePoolingClientConfiguration.builder();
builder.poolConfig(getGenericObjectPoolConfig());
// LettuceClientConfiguration.LettuceClientConfigurationBuilder builder = LettuceClientConfiguration.builder();
// builder.clientResources(clientResources());
// builder.commandTimeout(Duration.ofSeconds(3000));
LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(configuration, builder.build());
connectionFactory.afterPropertiesSet();
return connectionFactory;
}
}
使用方式
将工具类与配置结合
这样,我们注入RedisOfDatabaseOneUtil,就是一库了
private RedisTemplate createRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = getSerializerRedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.afterPropertiesSet();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// String 的序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
redisTemplate.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
redisTemplate.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
测试
项目在github



