Spring Redis

Spring对Redis进行了很好的封装,使用起来很简单。

创建一个工程

添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>	

创建实体,用于封装数据

import java.io.Serializable;

public class Phone implements Serializable {

    private static final long serialVersionUID = -2349104669272061557L;

    private int id;
    private String brand;
    private String model;
    private String color;

    public Phone() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Phone [id=" + id + ", brand=" + brand + ", model=" + model + ", color=" + color + "]";
    }

}	

配置连接工厂连接到Redis Server

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@SpringBootApplication
public class SpringRedisRestfulApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringRedisRestfulApplication.class, args);
    }

    /**
     * 配置Redis连接工厂
     * 
     * @return
     */
    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("192.168.2.128", 6379);
        return new JedisConnectionFactory(config);
    }

    /**
     * 定义RedisTemplate,用于实现DAO的操作
     * 
     * @return
     */
    @Bean
    RedisTemplate<String, Phone> redisTemplate() {
        RedisTemplate<String, Phone> redisTemplate = new RedisTemplate<String, Phone>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        return redisTemplate;
    }

}	

创建数据访问层

import java.util.Map;

import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class PhoneRepository {

    public static final String KEY = "ITEM";
    private RedisTemplate<String, Phone> redisTemplate;
    private HashOperations<String, Integer, Phone> hashOperations;

    /**
     * 使用构造方法注入
     * 
     * @param redisTemplate
     */
    public PhoneRepository(RedisTemplate<String, Phone> redisTemplate) {
        this.setRedisTemplate(redisTemplate);
        hashOperations = redisTemplate.opsForHash();
    }

    public Map<Integer, Phone> getAllPhones() {
        return hashOperations.entries(KEY);
    }

    public Phone getPhone(int id) {
        return (Phone) hashOperations.get(KEY, id);
    }

    public void addPhone(Phone phone) {
        hashOperations.put(KEY, phone.getId(), phone);
    }

    public void deletePhone(int id) {
        hashOperations.delete(KEY, id);
    }

    public void updatePhone(Phone phone) {
        addPhone(phone);
    }

    public RedisTemplate<String, Phone> getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate<String, Phone> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}	

创建控制器层

package w.sh.spring;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

@RestController
public class PhoneController {

    @Autowired
    PhoneRepository phoneRepository;

    @RequestMapping("/phones")
    @ResponseBody
    public ResponseEntity<Map<Integer, Phone>> getAllPhones() {
        Map<Integer, Phone> items = phoneRepository.getAllPhones();
        return new ResponseEntity<Map<Integer, Phone>>(items, HttpStatus.OK);
    }

    @GetMapping("/phones/{id}")
    @ResponseBody
    public ResponseEntity<Phone> getPhone(@PathVariable int id) {
        Phone phone = phoneRepository.getPhone(id);
        return new ResponseEntity<Phone>(phone, HttpStatus.OK);
    }

    @PostMapping(value = "/phones", consumes = { "application/json" }, produces = { "application/json" })
    @ResponseBody
    public ResponseEntity<Phone> addPhone(@RequestBody Phone phone, UriComponentsBuilder builder) {
        phoneRepository.addPhone(phone);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(builder.path("/phones/{id}").buildAndExpand(phone.getId()).toUri());
        return new ResponseEntity<Phone>(headers, HttpStatus.CREATED);
    }

    @PutMapping("/phones")
    @ResponseBody
    public ResponseEntity<Phone> updatePhone(@RequestBody Phone phone) {
        if (phone != null) {
            phoneRepository.updatePhone(phone);
        }
        return new ResponseEntity<Phone>(phone, HttpStatus.OK);
    }

    @DeleteMapping("/phones/{id}")
    @ResponseBody
    public ResponseEntity<Void> deletePhone(@PathVariable int id) {
        phoneRepository.deletePhone(id);
        return new ResponseEntity<Void>(HttpStatus.ACCEPTED);
    }
}

源码下载

spring-redis-restful.zip