总结:

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最佳实践的更多相关文章

  1. Spring Boot 2.x 整合 Redis最佳实践

    一.前言 在前面的几篇文章中简单的总结了一下Redis相关的知识.本章主要讲解一下 Spring Boot 2.0 整合 Redis.Jedis 和 Lettuce 是 Java 操作 Redis 的 ...

  2. PHP核心技术与最佳实践——全局浏览

    难得买到并喜欢一本好书,‘PHP核心技术与最佳实践’. 几天时间,先看了个大概,总结一下整体是什么样子的,怎么看怎么学. 1.总共14章: 2.第1.2章讲PHP的OOP: 其中第一章侧重于PHP的O ...

  3. 《开源安全运维平台OSSIM最佳实践》

    <开源安全运维平台OSSIM最佳实践> 经多年潜心研究开源技术,历时三年创作的<开源安全运维平台OSSIM最佳实践>一书即将出版.该书用80多万字记录了,作者10多年的IT行业 ...

  4. mongodb 最佳实践

    MongoDB功能预览:http://pan.baidu.com/s/1k2UfW MongoDB在赶集网的应用:http://pan.baidu.com/s/1bngxgLp MongoDB在京东的 ...

  5. celery最佳实践

    作为一个Celery使用重度用户.看到Celery Best Practices这篇文章.不由得菊花一紧. 干脆翻译出来,同一时候也会添加我们项目中celery的实战经验. 至于Celery为何物,看 ...

  6. React服务器渲染最佳实践

    源码地址:https://github.com/skyFi/dva-starter React服务器渲染最佳实践 dva-starter 完美使用 dva react react-router,最好用 ...

  7. Session 的原理及最佳实践

    Http协议是基于请求和响应的一种无状态的协议,而通过session可以使得Http应用变得有状态,即可以"记住"客户端的信息.今天就来说说这个session和cookie. Se ...

  8. MySQL面试必考知识点:揭秘亿级高并发数据库调优与最佳实践法则

    做业务,要懂基本的SQL语句: 做性能优化,要懂索引,懂引擎: 做分库分表,要懂主从,懂读写分离... 数据库的使用,是开发人员的基本功,对它掌握越清晰越深入,你能做的事情就越多. 今天我们用10分钟 ...

  9. Redis进阶实践之七Redis和Lua初步整合使用(转载 7)

    Redis进阶实践之七Redis和Lua初步整合使用 一.引言 Redis学了一段时间了,基本的东西都没问题了.从今天开始讲写一些redis和lua脚本的相关的东西,lua这个脚本是一个好东西,可以运 ...

随机推荐

  1. sqlite:多线程操作数据库“database is locked”解决方法

    1. 使sqlite支持多线程(不确定是否非加不可,暂且加上,以备后患) 可以在编译时/启动时/运行时选择线程模式,参考:http://www.cnblogs.com/liaj/p/4015219.h ...

  2. umount 卸载 无响应的 NFS 文件系统

    当NFS Client 无法访问 NFS Server的适合,在Client上df操作等就会挂起. 这个适合需要将挂载的NFS卸载掉.在不知道挂载点的情况下,可以使用nfsstat -m 命令来查看. ...

  3. python基础知识-列表,元组,字典

    列表(list) 赋值方法: l = [11,45,67,34,89,23] l = list() 列表的方法: #!/usr/bin/env python class list(object): & ...

  4. 【244】◀▶IEW-Unit09

    Unit 9 Food 1)Model1题目及范文讲解 In the world today, there is a problem with food production. As a result ...

  5. PCL类的设计结构

    博客转载自:http://www.pclcn.org/study/shownews.php?lang=cn&id=243 类和应用程序接口 对于PCL的大多数类而言,调用接口(所有public ...

  6. gcc -frandom-seed

    -frandom-seed=string This option provides a seed that GCC uses when it would otherwise use random nu ...

  7. Linux 之添加系统环境变量

    PATH 值是一系列目录,当执行命令时,linux就在这些目录下查找,其格式为: PATH=$PATH:<PATH1>:<PATH2>:<PATH3>:------ ...

  8. cassandra的命令

    cassandra的命令: connect <hostname>/<port> (<username> '<password>')?;    Conne ...

  9. C#Timer停不住

    System.Timers.Timer timer1 = new System.Timers.Timer(); timer1.Interval = ; //1天循环一次 timer1.Elapsed ...

  10. day03-CSS(1)

    一 .Css概念 CSS 指层叠样式表 (Cascading Style Sheets)(级联样式表) Css是用来美化html标签的,相当于页面化妆. ◆样式表书写位置 二. 选择器 1. 写法 选 ...