work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Spring Boot下Redis使用

Posted on 2020-07-01 16:37  work hard work smart  阅读(180)  评论(0编辑  收藏  举报

首先新建一个Spring Boot工程

1.pom.xml增加jedis

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.2</version>
</dependency>

  

2. 增加RedisConfig配置文件

@Configuration
public class RedisConfig {

    @Bean(name = "redisPool")
    public JedisPool jedisPool(@Value("${jedis.host}") String host,
                               @Value("${jedis.port}") int port){
        return  new JedisPool(host,port);
    }
}

  

3. 增加配置文件

 

  

4. 增加RedisClient类

@Component
public class RedisClient {

    @Resource(name="redisPool")
    private JedisPool jedisPool;

    public  void  set(String key, String value) throws  Exception{
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            jedis.set(key,value);
        }finally {
            if(jedis != null){
                jedis.close();
            }
        }
    }

    public String get(String key) throws  Exception{
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            return jedis.get(key);
        }finally {
            if(jedis != null){
                jedis.close();
            }
        }
    }
}

  

5. 增加CacheController测试

@Controller
@RequestMapping("/cache")
public class CacheController {

    @Autowired
    private  RedisClient redisClient;

    @RequestMapping("/set")
    @ResponseBody
    public  String set(@RequestParam("key") String key, @RequestParam("value") String value) throws Exception{
        redisClient.set(key,value);
        return  "Success";
    }

    @RequestMapping("/get")
    @ResponseBody
    public  String get(@RequestParam("key") String key) throws Exception{
       return   redisClient.get(key);
    }
}