• redis与Java交互


    可以直接导入Jedis框架,它能够实现Java与Redis数据库的交互


       
            redis.clients
            <artifactId>jedis
            4.0.0
       

    1. public static void main(String[] args) {
    2. //创建Jedis对象
    3. Jedis jedis = new Jedis("localhost", 6379);
    4. //使用之后关闭连接
    5. jedis.close();
    6. }

    jedis的方法与redis的命令基本相同,如果想执行redis命令只需执行相应的方法

    1. public static void main(String[] args) {
    2. try(Jedis jedis = new Jedis("localhost", 6379)){
    3. jedis.hset("person", "name", "sxc"); //等同于 hset hhh name sxc
    4. jedis.hset("person", "sex", "19"); //等同于 hset hhh age 19
    5. jedis.hgetAll("hhh").forEach((k, v) -> System.out.println(k+": "+v));
    6. }
    7. }

    SpringBoot整合Redis

    导入相应的starter,它底层没有用Jedis,而是Lettuce


        org.springframework.boot
        spring-boot-starter-data-redis

    starter提供的默认配置会去连接本地的Redis服务器,并使用0号数据库,可以手动进行修改配置

    spring:
      redis:
          #Redis服务器地址
        host: localhost
        #端口
        port: 6379
        #使用几号数据库
        database: 0

    starter已经提供了两个默认的模板类,StringRedisTemplate和RedisTemplate

    可以直接注入StringRedisTemplate来使用模板

    1. @Resource
    2. StringRedisTemplate template;
    3. @Test
    4. public void contextLoads() {
    5. Set keys = template.keys("*");
    6. assert keys != null;
    7. keys.forEach(System.out::println);
    8. }

    由于Spring没有专门的Redis事务管理器,但可以用JDBC提供的


        org.springframework.boot
        spring-boot-starter-jdbc


        mysql
        mysql-connector-java

    1. @Service
    2. public class RedisService {
    3. @Resource
    4. StringRedisTemplate template;
    5. @PostConstruct
    6. public void init(){
    7. template.setEnableTransactionSupport(true); //需要开启事务
    8. }
    9. @Transactional //需要添加此注解
    10. public void test(){
    11. template.multi();
    12. template.opsForValue().set("a", "1");
    13. template.exec();
    14. }
    15. }

    序列化存储对象时注意要实现Serializable接口

    也可以为RedisTemplate对象配置一个Serializer来实现对象的JSON存储,要导入jackson-bind包

    1. //注意Student需要实现序列化接口才能存入Redis
    2. template.opsForValue().set("student", new Student());
    3. System.out.println(template.opsForValue().get("student"));

  • 相关阅读:
    C++智能指针
    搭建Gitlab
    Verilog开源项目——百兆以太网交换机(三)Hash模块设计
    JVM(Java虚拟机) 整理(一):基础理论
    Xilinx 7系列FPGA的配置流程
    决策中心:构建企业长期战略竞争力
    elasticsearch实现聚合后两个字段相除相加相减相乘运算
    【无标题】
    【数据结构与算法】图的介绍和程序实现(含深度优先遍历、广度优先遍历)
    JS Promise 之 Hello World
  • 原文地址:https://blog.csdn.net/weixin_51992178/article/details/128068114