背景
最近在工作中接触并简单使用了redis缓存技术,本来以为会很难,至少让你的项目(我使用的是springboot项目)配置并使用起来还是so easy,但是要用好那就要另当别论了。
开发环境参数
intellij+jdk-8+spring-boot-1.5.3(不要忘了本地下载redis-server)
代码
1、创建spring-boot项目(参考:http://blog.csdn.net/xyc_csdn/article/details/67672198),创建项目(项目名称为redis)时记得勾选上web和redis两个依赖项;
2、项目创建完成后,在你的java代码包的根路径下创建包controller,注意controller包和RedisApplication属于同级,然后在controller包下创建类RedisController.java。目录结构如下:
3、进行编码
- RedisApplication.java
package com.xyc.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.nio.charset.Charset;
@SpringBootApplication
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
@Bean
public JedisConnectionFactory redisConnectionFactory() {
/**
* 使用JedisConnectionFactory的默认配置,可根据具体需求调整
* this.hostName = "localhost";
* this.port = 6379;
* this.timeout = 2000;
* this.usePool = true;
* this.useSsl = false;
* this.poolConfig = new JedisPoolConfig();
* this.dbIndex = 0;
* this.convertPipelineAndTxResults = true;
*/
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory());
redisTemplate.setKeySerializer(new StringRedisSerializer(Charset.forName("UTF8")));
return redisTemplate;
}
}
- RedisController.java
package com.xyc.redis.controller;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* Created by xyc on 2017/6/2 0002.
*/
@RestController
@RequestMapping("/redis")
public class RedisController {
@Resource
private RedisTemplate<String, Object> redisTemplate;
private static final String KEY = "KEY";
@RequestMapping("/index")
public String index() {
return "hello redis";
}
@RequestMapping("/set")
public String set(@RequestParam String value) {
this.redisTemplate.opsForValue().set(KEY, value);
return "set value success";
}
@RequestMapping("/get")
public String get() {
String value = (String) this.redisTemplate.opsForValue().get(KEY);
if (value == null) {
return "get value failed";
}
return "the value is " + value;
}
}
测试
首先测试controller是否可以正常访问
再测试是否可以将值放进redis
- 最后测试是否可以将值从redis中取出