spring-boot-starter-data-redis

来源:互联网 发布:mac 终端配置 编辑:程序博客网 时间:2024/04/20 10:58

GitHub:https://github.com/asd821300801/Spring-Boot/tree/spring-boot-redis


前期准备


  • 创建Spring Boot 工程

......


  • Maven 加入必要的依赖


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


  • application.properties


spring.redis.host=127.0.0.1spring.redis.port=6379spring.redis.password=123456spring.redis.database=0spring.redis.pool.max-active=8spring.redis.pool.max-wait=-1spring.redis.pool.max-idle=500spring.redis.pool.min-idle=0spring.redis.timeout=0


  • 启动redis


1



连接redis做相应的数据操作


查看源码可知 redisTemplateStringRedisTemplate已被自动配置,所以我们直接用就可以

org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration.class

2


RedisDao.java

import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Repository;@Repositorypublic class RedisDao {    @Autowired    private StringRedisTemplate template;    public  void setKey(String key,String value){        ValueOperations<String, String> ops = template.opsForValue();        ops.set(key,value);    }    public String getValue(String key){        ValueOperations<String, String> ops = this.template.opsForValue();        return ops.get(key);    }}


RedisController.java

import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.dao.RedisDao;@RestControllerpublic class RedisController {    @Autowired    private RedisDao redisDao;    @RequestMapping("/set")    public String set(String key,String value){        redisDao.setKey(key, value);        return "success";    }    @RequestMapping("/get")    public String get(String key){        return redisDao.getValue(key);    }}


访问测试


设置数据:http://localhost:8080/set?key=lingdu&value=123456

3


获取数据:http://localhost:8080/get?key=lingdu

4

原创粉丝点击