redis最佳实践
总结:
String类型的value(string/list/set/hash)使用StringRedisTemplate
其他类型的value(string/list/set/hash/object)使用RedisTemplate(GenericFastJsonRedisSerializer,value都会序列化为json)
value为string时,
如果使用RedisTemplate(使用GenericFastJsonRedisSerializer序列化)时,value值 带双引号。即:"遥远2"。
如果使用StringRedisTemplate,value值不带双引号。即:遥远2
1、pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<!-- <scope>provided</scope> -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
</dependencies>
2、application-dev.yml
spring:
redis:
host: 10.134.253.30
port: 6379
password: 123456
# 连接超时时间:ms
timeout: 5000
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
# 连接池中的最大空闲连接
max-idle: 8
# 连接池中的最小空闲连接
min-idle: 0
3、RedisConfig.java
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.StringRedisSerializer; import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer; @Configuration
public class RedisConfig { @Bean("jsonRedisTemplate")
public RedisTemplate<Object,Object> jsonRedisTemplate(RedisConnectionFactory redisConectionFactory) {
RedisTemplate<Object,Object> template = new RedisTemplate<Object,Object>();
template.setConnectionFactory(redisConectionFactory); template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericFastJsonRedisSerializer());
//hash
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericFastJsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
4、测试类
4.1、StringRedisTemplateTest
import java.util.List; import lombok.extern.slf4j.Slf4j; 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.BoundListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Slf4j
public class StringRedisTemplateTest { @Autowired
private StringRedisTemplate stringRedisTemplate; @Test
public void testValue() throws Exception {
stringRedisTemplate.opsForValue().set("zuo:1", "遥远2");
String val = stringRedisTemplate.opsForValue().get("zuo:1");
log.info("值={}",val);
}
@Test
public void testList() throws Exception {
stringRedisTemplate.opsForList().leftPush("list:zuo", "左");
stringRedisTemplate.opsForList().leftPush("list:zuo", "杨");
stringRedisTemplate.opsForList().leftPush("list:zuo", "王"); long len = stringRedisTemplate.opsForList().size("list:zuo");
for (int i = 0; i < len; i++) {
String val = stringRedisTemplate.opsForList().leftPop("list:zuo");//先进后出
/*
* 0:王
* 1:杨
* 2:左
*/
log.info("{}:{}",i,val);
}
}
@Test
public void testHash() throws Exception {
stringRedisTemplate.opsForHash().put("hash:zuo", "name", "遥远2");;
stringRedisTemplate.opsForHash().put("hash:zuo", "age", "18");
String age = (String)stringRedisTemplate.opsForHash().get("hash:zuo", "age");
log.info("{}",age);
}
@Test
public void testSet() throws Exception {
stringRedisTemplate.opsForSet().add("set:zuo", "1");
stringRedisTemplate.opsForSet().add("set:zuo", "2");
stringRedisTemplate.opsForSet().add("set:zuo", "3");
long len = stringRedisTemplate.opsForSet().size("set:zuo");
for (int i = 0; i < len; i++) {
String s = stringRedisTemplate.opsForSet().pop("set:zuo");
log.info("{}",s);
}
}
@Test
public void testBound() throws Exception {
BoundListOperations operations = stringRedisTemplate.boundListOps("list:zuo");
operations.leftPush("左");
operations.leftPush("杨");
operations.leftPush("王"); List<String> list = operations.range(0, operations.size());
list.stream().forEach(s -> System.out.println(s));
} }
4.2、RedisTemplateTest
import lombok.extern.slf4j.Slf4j; 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.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner; import com.ebc.entity.User;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Slf4j
public class RedisTemplateTest {
@Autowired
private RedisTemplate<Object,Object> jsonRedisTemplate;//不能为RedisTemplate<K,V>
@Test
public void testHash() throws Exception {
String key = "redistemplate:hash";
jsonRedisTemplate.opsForHash().put(key, "name", "遥远2");
jsonRedisTemplate.opsForHash().put(key, "age", 18);
int age = (Integer)jsonRedisTemplate.opsForHash().get(key, "age");
log.info("{}", age);
}
@Test
public void testObj() throws Exception {
String key = "redistemplate:user";
jsonRedisTemplate.delete(key);
jsonRedisTemplate.opsForValue().set(key, User.getSampleUser()); User user = (User)jsonRedisTemplate.opsForValue().get(key);
log.info("{}", user);
} }
4.3、RedisTemplateTest2
import java.util.List; import lombok.extern.slf4j.Slf4j; 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.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Slf4j
public class RedisTemplateTest2 { @Autowired()
private RedisTemplate<Object,Object> jsonRedisTemplate; @Test
public void testValue() throws Exception {
jsonRedisTemplate.opsForValue().set("redistemplate:value:int", 1);
jsonRedisTemplate.opsForValue().set("redistemplate:value:long", 1L);
jsonRedisTemplate.opsForValue().set("redistemplate:value:double", 1d); int i = (int)jsonRedisTemplate.opsForValue().get("redistemplate:value:int");
long l = (long)jsonRedisTemplate.opsForValue().get("redistemplate:value:long");
double d = (double)jsonRedisTemplate.opsForValue().get("redistemplate:value:double"); log.info("{},{},{}",i,l,d);
}
@Test
public void testList() throws Exception {
String key = "redistemplate:list";
jsonRedisTemplate.opsForList().leftPush(key, 1);
jsonRedisTemplate.opsForList().leftPush(key, 2);
jsonRedisTemplate.opsForList().leftPush(key, 3); long len = jsonRedisTemplate.opsForList().size(key);
for (int i = 0; i < len; i++) {
int val = (int)jsonRedisTemplate.opsForList().leftPop(key);//先进后出
/*
* 0:3
* 1:2
* 2:1
*/
log.info("{}:{}",i,val);
}
}
@Test
public void testSet() throws Exception {
String key = "redistemplate:set";
jsonRedisTemplate.opsForSet().add(key, 1);
jsonRedisTemplate.opsForSet().add(key, 2);
jsonRedisTemplate.opsForSet().add(key, 3);
long len = jsonRedisTemplate.opsForSet().size(key);
for (int i = 0; i < len; i++) {
int s = (int)jsonRedisTemplate.opsForSet().pop(key);
log.info("{}",s);
}
}
@Test
public void testBound() throws Exception {
BoundListOperations operations = jsonRedisTemplate.boundListOps("redistemplate:list");
operations.leftPush(1);
operations.leftPush(2);
operations.leftPush(3); List<Integer> list = operations.range(0, operations.size());
list.stream().forEach(s -> System.out.println(s));
} }
redis最佳实践的更多相关文章
- Spring Boot 2.x 整合 Redis最佳实践
一.前言 在前面的几篇文章中简单的总结了一下Redis相关的知识.本章主要讲解一下 Spring Boot 2.0 整合 Redis.Jedis 和 Lettuce 是 Java 操作 Redis 的 ...
- PHP核心技术与最佳实践——全局浏览
难得买到并喜欢一本好书,‘PHP核心技术与最佳实践’. 几天时间,先看了个大概,总结一下整体是什么样子的,怎么看怎么学. 1.总共14章: 2.第1.2章讲PHP的OOP: 其中第一章侧重于PHP的O ...
- 《开源安全运维平台OSSIM最佳实践》
<开源安全运维平台OSSIM最佳实践> 经多年潜心研究开源技术,历时三年创作的<开源安全运维平台OSSIM最佳实践>一书即将出版.该书用80多万字记录了,作者10多年的IT行业 ...
- mongodb 最佳实践
MongoDB功能预览:http://pan.baidu.com/s/1k2UfW MongoDB在赶集网的应用:http://pan.baidu.com/s/1bngxgLp MongoDB在京东的 ...
- celery最佳实践
作为一个Celery使用重度用户.看到Celery Best Practices这篇文章.不由得菊花一紧. 干脆翻译出来,同一时候也会添加我们项目中celery的实战经验. 至于Celery为何物,看 ...
- React服务器渲染最佳实践
源码地址:https://github.com/skyFi/dva-starter React服务器渲染最佳实践 dva-starter 完美使用 dva react react-router,最好用 ...
- Session 的原理及最佳实践
Http协议是基于请求和响应的一种无状态的协议,而通过session可以使得Http应用变得有状态,即可以"记住"客户端的信息.今天就来说说这个session和cookie. Se ...
- MySQL面试必考知识点:揭秘亿级高并发数据库调优与最佳实践法则
做业务,要懂基本的SQL语句: 做性能优化,要懂索引,懂引擎: 做分库分表,要懂主从,懂读写分离... 数据库的使用,是开发人员的基本功,对它掌握越清晰越深入,你能做的事情就越多. 今天我们用10分钟 ...
- Redis进阶实践之七Redis和Lua初步整合使用(转载 7)
Redis进阶实践之七Redis和Lua初步整合使用 一.引言 Redis学了一段时间了,基本的东西都没问题了.从今天开始讲写一些redis和lua脚本的相关的东西,lua这个脚本是一个好东西,可以运 ...
随机推荐
- html5常用模板下载网站
html5常用模板下载网站 开创者素材.站长素材.模板之家 推荐葡萄家园素材网,他们网页模板栏目有个HTML模板,很多静态源码.应该是你所需要的. html静态页面模板 还是服饰素材啊 朋友 设计云 ...
- 分享知识-快乐自己:Mybatis缓存机制
论缓存机制: 1):mybatis 提供了缓存机制减轻数据库压力,提高数据库性能. 2):mybatis 的缓存分为两级:一级缓存.二级缓存 3):一级缓存是SqlSession级别的缓存,缓存的数据 ...
- LoadRunner中的函数
函数是LoadRunner提供给性能测试工程师的利器,有了它,性能测试工程师可以对脚本进行更为自由的开发,更适应实际测试的需求,进一步扩展脚本的功能. LoadRunner函数的格式: 返回值 函数 ...
- java 基础 - 查找某个字串出现的次数及位置
查找某个字串出现的次数及位置 public class search { public static void main(String[] args){ String str = "abc1 ...
- listen 72
Warmer Temps May Bollux Botanicals Global warming might seem like a botanical boon. After all, milde ...
- linux进程学习-进程描述符,控制块
从数据结构的角度,进程用task_struct结构来描述,称为“进程描述符 (Process Descriptor)”或者“进程控制块(Process Control Block, PCB)”,其包含 ...
- ACM学习历程—HDU5269 ZYB loves Xor I(位运算 && dfs && 排序)(BestCoder Round #44 1002题)
Problem Description Memphis loves xor very musch.Now he gets an array A.The length of A is n.Now he ...
- bzoj 2251: 外星联络 后缀Trie
题目大意 http://www.lydsy.com/JudgeOnline/problem.php?id=2251 题解 本来以为这道题应该从01序列的性质入手 结果就想歪了 等自己跳出了01序列这个 ...
- 洛谷 P2962 [USACO09NOV]灯Lights
题目描述 Bessie and the cows were playing games in the barn, but the power was reset and the lights were ...
- Java对象序列化详解
深入理解Java对象序列化 1. 什么是Java对象序列化 Java平台允许我们在内存中创建可复用的Java对象,但一般情况下,只有当JVM处于运行时,这些对象才可能存在,即,这些对象的生命周期不会比 ...