1导入包
<!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <!-- 不依赖rdisde 异步客户端lettuce--> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <!--引入redis客服端驱动--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>
2,设置初始化
//注入reidstempate @Autowired private RedisTemplate redisTemplate=null; //自定义初始化方法 @PostConstruct public void init(){ initeRedisTemplate(); } //设置redistempplte序列化,存入的值不是二进制 private void initeRedisTemplate(){ RedisSerializer stringSerializer=redisTemplate.getStringSerializer(); redisTemplate.setKeySerializer(stringSerializer); redisTemplate.setHashKeySerializer(stringSerializer); redisTemplate.setValueSerializer(stringSerializer); } public static void main(String[] args) { SpringApplication.run(ChapterApplication.class, args); }
3,写代码Controller
@Controller @RequestMapping("/s") public class RedisController { @Autowired private RedisTemplate redisTemplate=null; @Autowired private StringRedisTemplate stringRedisTemplate=null; @RequestMapping("/s1") @ResponseBody public Map<String,Object> testStringAndHash(){ redisTemplate.opsForValue().set("key1","value1"); redisTemplate.opsForValue().set("int_ket","1"); stringRedisTemplate.opsForValue().set("int","1"); //使用运算符 stringRedisTemplate.opsForValue().increment("int",1); //获取底层jedis链接 Jedis jedis=(Jedis) stringRedisTemplate.getConnectionFactory().getConnection().getNativeConnection(); //减1操作 redistemplate不支持 jedis.decr("int"); Map<String,String> hash=new HashMap<String,String>(); hash.put("field1","value1"); hash.put("field2","value2"); //存入散列类型 stringRedisTemplate.opsForHash().putAll("hash",hash); //新增一个字段 stringRedisTemplate.opsForHash().put("hash","field3","calue3"); //绑定散列惭怍key 操作整个散列数据 BoundHashOperations hashOps=stringRedisTemplate.boundHashOps("hash"); //删除2个字段 hashOps.delete("field1","field2"); //新增一个字段 hashOps.put("field4","value4"); Map<String,Object> map=new HashMap<String,Object>(); map.put("success",true); return map; } }