springboot集成redis

下载redis的windows安装包并安装

安装redis客户端Redis Desktop Manager

代码编写

  1. 新建StudentController类,并写入:

    package com.dj.app.springboot.web;

    import com.dj.app.springboot.service.StudentService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;

    @Controller
    public class StudentController {
    @Autowired
    private StudentService studentService;
    // 存
    @RequestMapping(value = "/put")
    public @ResponseBody Object put(String key, String value) {
    studentService.put(key, value);
    return "值已存进redis";
    }

    // 取
    @RequestMapping(value = "/get")
    public @ResponseBody String get() {
    String name = studentService.get("name");
    return "数据为:" + name;
    }
    }
  2. 新建StudentService接口类,并写入:

    package com.dj.app.springboot.service;

    public interface StudentService {
    /**
    * 将值存进redis
    * @param key
    * @param value
    */
    void put(String key, String value);
    String get(String name);
    }
  3. 新建StuentServiceImpl实现类,并写入:

    package com.dj.app.springboot.service.impl;

    import com.dj.app.springboot.service.StudentService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Service;

    @Service
    public class StudentServiceImpl implements StudentService {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public void put(String key, String value) {
    redisTemplate.opsForValue().set(key, value);
    }

    @Override
    public String get(String name) {
    String res = (String) redisTemplate.opsForValue().get(name);
    return res;
    }
    }
  4. 在application.yml中,配置redis:

    spring:
    # 设置redis
    redis:
    port: 6379
    host: localhost
  5. 启动,并输入:localhost:8080/put?key=name&value=zhangsan,localhost:8080/get能看到结果

springboot集成lombok

安装lombok

  1. 引入jar包
    <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
    </dependency>
  2. 启用lombok
    File => Settings => Build, Execution, Deployment => Compiler => Annotation Processors

    勾选 Enable annotation processing
  3. 安装lombok插件
    File => Settings => Plugins, 搜索lombok下载

    代码编写

    # 新建UserInfo2.class类

    @Setter @Getter // 自动生成成员变量的get和set方法
    public class UserInfo2 {
    private Long id;
    private String name;
    private String phone;
    private String address;
    }

    # 新建使用方法App.class
    public class App {
    public static void main(String[] args) {
    UserInfo2 userInfo2 = new UserInfo2();
    }
    }

    详细教程点击这里:lombok教程