redis use

Dapeng 2022-08-06 13:34:17 阅读数:448

redisuse

jedis (使用 java 代码连接 redis)

添加依赖

<!-- jedis依赖 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>

java 代码

@RequestMapping("/")
public String test(){

// 建立与 redis 的连接,与 JDBC 类似
// Jedis jedis = new Jedis(host,port); 两个参数,host:redis的ip地址,port:端口号
Jedis jedis = new Jedis("124.222.157.68",6379);
// 验证密码 :If there is no password, don't need this step
// jedis.auth("123");
// 往 redis 中存一个 String 类型的值
jedis.set("test","123");
// 取出 String 类型的值
String str = jedis.get("test");
System.out.println("存储的 String 类型的值为 : "+str);
// 往 redis 中存一个 list 类型的值
jedis.lpush("testList","a","b","c");
// 取出 list 类型的值
List<String> list = jedis.lrange("testList", 0, -1);
System.out.println("存储的 list 类型的值为 : ");
for (String string:list) {

System.out.print(string+",");
}
return "hello!";
}

执行效果

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

springboot Projects using tools to data stored in redis 中

依赖

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

In the project start up on the class cache

在这里插入图片描述

配置 application 文件

# Set the cache mode for redis
spring.cache.type=redis
# Set the length of the cache data,单位毫秒
spring.cache.redis.time-to-live=60000
# 是否缓存空值
spring.cache.redis.cache-null-values=false
# 配置redis ip地址
spring.redis.host=124.222.157.68
# 设置redis密码
# spring.redis.password=123

封装工具类

The configuration class is added in the project,After configuration cache time here,applicationIn the file cache time will be overwritten,Now don't need to implement serialization in the entity class can also,Because the tools use isjson的序列化,没有用到io序列化.

Utility classes the datajson序列化,在redisDisplay data through

package com.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

//修改RedisTemplate的序列化
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
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;
}
/** * json序列化 * * @return */
public RedisSerializer<Object> jackson2JsonRedisSerializer() {

// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
return serializer;
}
//Modify the annotation serialization,不能修改RedisTemplate的序列化
@Bean
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {

// 生成一个默认配置,通过config对象即可对缓存进行自定义配置
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
config = config
// 设置 key为string序列化
.serializeKeysWith(
RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
// 设置value为json序列化
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()))
// 不缓存空值
.disableCachingNullValues()
// 设置缓存的默认过期时间 30分钟
.entryTtl(Duration.ofMinutes(30L));
// 特殊缓存空间应用不同的配置
Map<String, RedisCacheConfiguration> map = new HashMap<>();
map.put("provider1", config.entryTtl(Duration.ofMinutes(30L)));// provider1缓存空间过期时间 30分钟
map.put("provider2", config.entryTtl(Duration.ofHours(1L)));// provider2缓存空间过期时间 1小时
// 使用自定义的缓存配置初始化一个RedisCacheManager
RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory).cacheDefaults(config) // 默认配置
.withInitialCacheConfigurations(map) // 特殊缓存
.transactionAware() // 事务
.build();
return cacheManager;
}
}

Specify the data deposited in the redis

package com.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
/** * @author Han Kunpeng * @data 2022/7/25 */
@RestController
public class TestController {

@Autowired
private RedisTemplate redisTemplate;
/** * 存入值 * @return */
@RequestMapping("/")
private Object addOrder() {

//将订单id存入redis,存30分钟 ;
//redisTemplate.opsForValue()Say you want to deposit the data type of the
//value 表示是字符串类型
/** TimeUnit.SECONDS:秒 TimeUnit.MINUTES:分 TimeUnit.HOURS:时 TimeUnit.DAYS:日 TimeUnit.MILLISECONDS:毫秒 TimeUnit.MILLISECONDS:微秒 TimeUnit.NANOSECONDS:纳秒 */
redisTemplate.opsForValue().set("testRedis","redis",60, TimeUnit.SECONDS);
return "存入成功";
}
/** * Get keys * @return */
@PostMapping("/time")
private Object getOrderTime() {

Long time=redisTemplate.getExpire("testRedis");
return "Success take time : "+time;
}
/** * 删除键 * @return */
@DeleteMapping("/del")
public Object deleteKey(){

return redisTemplate.delete("testRedis");
}
}
Long time=redisTemplate.getExpire("testRedis");
return "Success take time : "+time;
}
/** * 删除键 * @return */
@DeleteMapping("/del")
public Object deleteKey(){

return redisTemplate.delete("testRedis");
}
}
copyright:author[Dapeng],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/218/202208061327435824.html