redis 客户端集成业务代码,是我们项目开发中最终面对的,今天我们从头到尾给大家演示一下,起到一个抛砖引玉的作用。
1、中文官网进去:Redis客户端连接工具资料 -- Redis中文网 -- Redis中国用户组(CRUG)
选择java
进入:
发现有这么多客户端类型可以连接到redis:
2、点击Jedis后进入相应Github,GitHub - redis/jedis: Redis Java client designed for performance and ease of use.
jedis连接线程不安全可以引入连接池,每个客户都来了都从池中取一个连接。
这里面有使用详情,可以详细阅读。
4、进入spring官网:
选择redis模块:
springboot 里面也有redis相关 点击springboot:
Spring Data 搜索reids
点击文档进入:
这里面就是使用详情:Spring Data Redis
并且支持tettuce和jedis
springboot 里面也有配置:
来到:
5、实战操作:
pom文件引入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
1)查询客户端:CONFIG get *
2)修改 成远端可以访问
6、默认是二进制字节流:
保存查询:
import org.springframework.data.redis.core.RedisTemplate;//原生的模版
@Autowired
RedisTemplate redisTemplate;
@Autowired
@Qualifier("commonStringRedisTemplate")//方法名注解
StringRedisTemplate stringRedisTemplate;
@Autowired
ObjectMapper objectMapper;
public void testRedis(){
redisTemplate.opsForValue().set("hello","china");
System.out.println(redisTemplate.opsForValue().get("hello"));
// stringRedisTemplate.opsForValue().set("hello01","china");
// System.out.println(stringRedisTemplate.opsForValue().get("hello01"));
}
2)查看:
3)更底层的获取连接:
RedisConnection conn = redisTemplate.getConnectionFactory().getConnection();
conn.set("hello02".getBytes(),"mashibing".getBytes());
System.out.println(new String(conn.get("hello02".getBytes())));
7、json转化:使用这个StringRedisTemplate 模版时要做json序列化配置
pom文件引入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
1)配置:
@Configuration
public class CommonTemplate {
@Bean
public StringRedisTemplate commonStringRedisTemplate(RedisConnectionFactory fc){
StringRedisTemplate tp = new StringRedisTemplate(fc);
tp.setHashValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
return tp ;
}
}
2)业务引用:
@Autowired
@Qualifier("commonStringRedisTemplate")//方法名注解
StringRedisTemplate stringRedisTemplate;
具体API操作和以前一样。
3)换成Jackson2HashMapper 配置:
先引用:
@Autowired
ObjectMapper objectMapper;
然后:
Jackson2HashMapper jm = new Jackson2HashMapper(objectMapper, false);
stringRedisTemplate.opsForHash().putAll("sean01",jm.toHash(p));
Map map = stringRedisTemplate.opsForHash().entries("sean01");
Person per = objectMapper.convertValue(map, Person.class);
System.out.println(per.getName());
8、消息订阅:
1)发送角色:
stringRedisTemplate.convertAndSend("ooxx","hello");
2)接收角色:
3)发送角色:
接收角色:
RedisConnection cc = stringRedisTemplate.getConnectionFactory().getConnection();
cc.subscribe(new MessageListener() {
@Override
public void onMessage(Message message, byte[] pattern) {
byte[] body = message.getBody();
System.out.println(new String(body));
}
}, "ooxx".getBytes());
while(true){
stringRedisTemplate.convertAndSend("ooxx","hello from nandao ");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
到此,redis的实战操作整个流程演示了一遍,大家在项目中一定多测试、多查看资料,定会很快掌握。