Redis学习(4)Jedis、Springboot整合

    技术2025-04-17  14

    1、通过jedis实现事务控制

    总体流程和redis命令行操作相似,一下不做赘述,有需要可看Redis学习(3)

    import com.alibaba.fastjson.JSONObject; import redis.clients.jedis.Jedis; import redis.clients.jedis.Transaction; public class testPing { public static void main(String[] args) { Jedis jedis = new Jedis("192.168.240.128",6379); JSONObject jsonObject = new JSONObject(); jsonObject.put("hello","world"); jsonObject.put("name","wj"); //开启事务 jedis.flushDB(); jedis.watch("user1"); Transaction multi = jedis.multi(); String s = jsonObject.toJSONString(); try { multi.set("user1",s); multi.set("user2",s); // int i = 1/0; multi.exec(); } catch (Exception e) { multi.discard(); e.printStackTrace(); }finally { System.out.println(jedis.get("user1")); System.out.println(jedis.get("user2")); jedis.close(); } } }

    2、springboot整合

    springboot2.x之后jedis被替换为lettuce jedis:直连,多线程操作时不安全 lettue:使用netty,不存在线程不安全情况

    (1)导入依赖

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

    (2)对redis进行配置:

    1、先进入spring-boot-autoconfigure-2.3.1.RELEASE.jar,打开spring.factories 输入redis搜索,ctrl点击进入下图自动配置类 进入配置类后就可以找到redis的配置文件 配置文件中有很多相关的配置字段,可以自行查看,以下为最基础的redis配置信息:

    # 最基本的redis配置 spring.redis.host=192.168.240.128 spring.redis.port=6379

    (3)测试类编写:

    首先要导入RedisAutoConfiguration 其中一个配置类RedisTemplate或者StringRedisTemplate

    public class RedisAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "redisTemplate") public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); return template; } @Bean @ConditionalOnMissingBean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { StringRedisTemplate template = new StringRedisTemplate(); template.setConnectionFactory(redisConnectionFactory); return template; } }

    以下为测试类实现内容

    import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisTemplate; @SpringBootTest class Redis02SpringbootApplicationTests { @Autowired private RedisTemplate redisTemplate; @Test void contextLoads() { /** * RedisTemplate 操作不同数据类型 * 每一个操作对应一个数据类型 * opsForValue 操作字符串==>String * opsForList * opsForSet * opsForHash * opsForZSet * opsForGeo * opsForHyperLogLog */ //获取redis的连接对象 // RedisConnection connection = redisTemplate.getConnectionFactory().getConnection(); // connection.flushAll(); // connection.flushDb(); redisTemplate.opsForValue().set("a","wj"); System.out.println(redisTemplate.opsForValue().get("a")); } }
    Processed: 0.011, SQL: 9