首先新建一个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); } }