本文共 3307 字,大约阅读时间需要 11 分钟。
1、导入对应的依赖
redis.clients jedis 3.2.0 com.alibaba fastjson 1.2.62 commons-pool commons-pool 1.6
public static void main(String[] args){ Jedis jedis = new Jedis("39.96.113.156", 6379);// 设置密码 jedis.auth("26993958a"); jedis.flushDB(); JSONObject jsonObject = new JSONObject(); jsonObject.put("hello","world"); jsonObject.put("name","kuangshen"); System.out.println(jedis.ping()); // 开启事务 Transaction multi = jedis.multi(); String result = jsonObject.toJSONString(); // jedis.watch(result) try { multi.set("user1",result); multi.set("user2",result); multi.exec(); // 执行事务! } catch (Exception e) { multi.discard(); // 放弃事务 e.printStackTrace(); } finally { System.out.println(jedis.get("user1")); System.out.println(jedis.get("user2")); jedis.close(); // 关闭连接 } }
SpringBoot 操作数据:spring-data jpa jdbc mongodb redis!
SpringData 也是和 SpringBoot 齐名的项目! 说明: 在 SpringBoot2.x 之后,原来使用的jedis 被替换为了 lettuce? jedis : 采用的直连,多个线程操作的话,是不安全的,如果想要避免不安全的,使用 jedis pool 连接 池! 更像 BIO 模式 lettuce : 采用netty,实例可以再多个线程中进行共享,不存在线程不安全的情况!可以减少线程数据 了,更像 NIO 模式 源码分析:@Configuration(proxyBeanMethods = false)@ConditionalOnClass(RedisOperations.class)@EnableConfigurationProperties(RedisProperties.class)@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })public class RedisAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "redisTemplate") // 我们可以自己定义一个 redisTemplate来替换这个默认的! public RedisTemplate
1.导入依赖
org.springframework.boot spring-boot-starter-data-redis
2.配置连接
spring.redis.host=xxxxxxxspring.redis.port=xxxxxxxspring.redis.password=xxxxxxx
3.测试
@Test public void contextLoads() { // opsForValu操作字符串 redisTemplate.opsForValue().set("name","chenshengming"); String name = (String)redisTemplate.opsForValue().get("name"); System.out.println(name);// 返回Redis的链接对象 RedisConnection redisConnection=redisTemplate.getConnectionFactory().getConnection(); redisConnection.flushDb(); redisConnection.flushAll(); }4.关于对象的保存: 5.我们来编写一个自己的 RedisTemplete
转载地址:http://emrwi.baihongyu.com/