Springboot Integrated native Redis

Source: Internet
Author: User
Tags serialization

One of the uses of Redis is Spring-data-redis, which is described earlier.

This article describes native Redis, also known as Jedis. This is more efficient.

1.maven Introduction of dependency

<!--springboot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
  <!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

<!--Druid Pool-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.5</version>
</dependency>

<!--redis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>

<!--json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.38</version>
</dependency>

2. Configure the data source in Application.properties

# MyBatis
#别名
Mybatis.type-aliases-package=com.imooc.miaosha.domain
#mybatis默认是属性名和数据库字段名一一对应的, i.e.
#数据库表列: User_name
#实体类属性: User_name
#但是java中一般使用驼峰命名
#数据库表列: User_name
#实体类属性: UserName
#在Springboot中, the Hump function can be turned on by setting the Map-underscore-to-camel-case property to True.
#mybatis. Configuration.mapunderscoretocamelcase property is true also open hump, and higher priority
Mybatis.configuration.mapunderscoretocamelcase=true
mybatis.configuration.default-fetch-size=100
mybatis.configuration.default-statement-timeout=3000
#扫描映射文件
Mybatis.mapperlocations = Classpath:com/imooc/miaosha/dao/*.xml
# Druid
Spring.datasource.url=jdbc:mysql://192.168.220.128:3306/miaosha?useunicode=true&characterencoding=utf-8 &allowmultiqueries=true&usessl=false
Spring.datasource.username=root
spring.datasource.password=123456
Spring.datasource.driver-class-name=com.mysql.jdbc.driver
Spring.datasource.type=com.alibaba.druid.pool.druiddatasource
Spring.datasource.filters=stat
spring.datasource.maxactive=2
Spring.datasource.initialsize=1
spring.datasource.maxwait=60000
Spring.datasource.minidle=1
spring.datasource.timebetweenevictionrunsmillis=60000
spring.datasource.minevictableidletimemillis=300000
Spring.datasource.validationquery=select ' x '
Spring.datasource.testwhileidle=true
Spring.datasource.testonborrow=false
Spring.datasource.testonreturn=false
Spring.datasource.poolpreparedstatements=true
Spring.datasource.maxopenpreparedstatements=20
#redis
redis.host=192.168.220.128
redis.port=6379
Redis.timeout=3
redis.password=123456
redis.poolmaxtotal=10
redis.poolmaxidle=10
Redis.poolmaxwait=3

3. Package Reids
Step One: Write a Redis file with Redisconfig.java load configuration
/**
* Load Read configuration file
*/
@Component
@ConfigurationProperties (prefix= "Redis")//scan configuration file to extract properties starting with Redis
public class Redisconfig {
Private String host;
private int port;
private int timeout;//seconds, not milliseconds
private String password;
private int poolmaxtotal;
private int poolmaxidle;
private int poolmaxwait;//seconds
Public String GetHost () {
return host;
}
public void Sethost (String host) {
This.host = host;
}
public int Getport () {
return port;
}
public void Setport (int port) {
This.port = port;
}
public int gettimeout () {
return timeout;
}
public void setTimeout (int timeout) {
This.timeout = timeout;
}
Public String GetPassword () {
return password;
}
public void SetPassword (String password) {
This.password = password;
}
public int getpoolmaxtotal () {
return poolmaxtotal;
}
public void setpoolmaxtotal (int poolmaxtotal) {
This.poolmaxtotal = Poolmaxtotal;
}
public int Getpoolmaxidle () {
return poolmaxidle;
}
public void Setpoolmaxidle (int poolmaxidle) {
This.poolmaxidle = Poolmaxidle;
}
public int getpoolmaxwait () {
return poolmaxwait;
}
public void setpoolmaxwait (int poolmaxwait) {
this.poolmaxwait = poolmaxwait;
}
}

Step Two: Write Redispoolfactory.java get Redispool

/**
* Get REDISPO
*/
@Service
public class Redispoolfactory {

@Autowired
Redisconfig Redisconfig;

@Bean
Public Jedispool jedispoolfactory () {
Jedispoolconfig poolconfig = new Jedispoolconfig ();
Poolconfig.setmaxidle (Redisconfig.getpoolmaxidle ());
Poolconfig.setmaxtotal (Redisconfig.getpoolmaxtotal ());
Poolconfig.setmaxwaitmillis (redisconfig.getpoolmaxwait () * 1000);
Jedispool JP = new Jedispool (Poolconfig, Redisconfig.gethost (), Redisconfig.getport (),
Redisconfig.gettimeout () *1000, Redisconfig.getpassword (), 0); The//database property is that Redis supports multiple libraries, the default 16 libraries, and the index starts at 0
return JP;
}

}

Step three: Define the build strategy for Redis key. General use Interface+abstract+extends

/**
* Key Interface
*/
Public interface Keyprefix {

public int expireseconds ();//Expiry time

Public String getprefix ();

}


/**
* Abstract class of key
* Abstract classes are variables and methods that can define private, and cannot be objects
* The interface is all public
*/
Public abstract class Baseprefix implements keyprefix{

private int expireseconds;//Expiration time

Private String Prefix;//key Value

Public Baseprefix (String prefix) {//0 means never expires
This (0, prefix);
}

Public Baseprefix (int expireseconds, String prefix) {
This.expireseconds = Expireseconds;
This.prefix = prefix;
}

public int expireseconds () {//default 0 means never expires
return expireseconds;
}

Public String Getprefix () {
String className = GetClass (). Getsimplename ();
Return classname+ ":" + prefix;//class name +
}

}

/**
* User Class Key implementation
*/
public class UserKey extends baseprefix{

Private UserKey (String prefix) {
Super (prefix);
}
public static UserKey getById = new UserKey ("id");
public static UserKey Getbyname = new UserKey ("name");
}

4. Write Redisservice.java provides Redis service, mainly get (), set (), exists (), serialization, deserialization,
Be sure to return to the pool after using the Redis link.


@Service
public class Redisservice {

Annotations recommend the use of @resource, need to guide the package
@Autowired
Jedispool Jedispool;

/**
* Get an Object
* */
Public <T> T Get (keyprefix prefix, String key, class<t> clazz) {
Jedis Jedis = null;
try {
Jedis = Jedispool.getresource ();
Generate a real key
String Realkey = prefix.getprefix () + key;
String str = jedis.get (Realkey);
T t = Stringtobean (str, clazz);
return t;
}finally {
Returntopool (Jedis);
}
}

/**
* Set Object
* */
Public <T> Boolean set (Keyprefix prefix, String key, T value) {
Jedis Jedis = null;
try {
Jedis = Jedispool.getresource ();
String str = beantostring (value);
if (str = = NULL | | str.length () <= 0) {
return false;
}
Generate a real key
String Realkey = prefix.getprefix () + key;
int seconds = Prefix.expireseconds ();
if (seconds <= 0) {//Determine expiration time
Jedis.set (Realkey, str);
}else {
Jedis.setex (Realkey, seconds, str);//Set a key value and set an expiration time
}
return true;
}finally {
Returntopool (Jedis);
}
}

/**
* Determine if key exists
* */
Public <T> Boolean exists (Keyprefix prefix, String key) {
Jedis Jedis = null;
try {
Jedis = Jedispool.getresource ();
Generate a real key
String Realkey = prefix.getprefix () + key;
Return jedis.exists (Realkey);
}finally {
Returntopool (Jedis);
}
}

/**
* Add Value
* */
Public <T> Long incr (keyprefix prefix, String key) {
Jedis Jedis = null;
try {
Jedis = Jedispool.getresource ();
Generate a real key
String Realkey = prefix.getprefix () + key;
Return JEDIS.INCR (Realkey);
}finally {
Returntopool (Jedis);
}
}

/**
* Reduced value
* */
Public <T> Long decr (keyprefix prefix, String key) {
Jedis Jedis = null;
try {
Jedis = Jedispool.getresource ();
Generate a real key
String Realkey = prefix.getprefix () + key;
Return JEDIS.DECR (Realkey);
}finally {
Returntopool (Jedis);
}
}

/**
* Serialization
* @param value
* @param <T>
* @return
*/
Private <T> String beantostring (T value) {
if (value = = null) {
return null;
}
Class<?> clazz = Value.getclass ();
if (clazz = = Int.class | | clazz = = integer.class) {
Return "" +value;
}else if (clazz = = String.class) {
Return (String) value;
}else if (clazz = = Long.class | | clazz = = long.class) {
Return "" +value;
}else {
return json.tojsonstring (value);
}
}

/**
* Deserialization
* @param str
* @param clazz
* @param <T>
* @return
*/
@SuppressWarnings ("Unchecked")
Private <T> T Stringtobean (String str, class<t> clazz) {
if (str = = NULL | | str.length () <= 0 | | clazz = = NULL) {
return null;
}
if (clazz = = Int.class | | clazz = = integer.class) {
Return (T) integer.valueof (str);
}else if (clazz = = String.class) {
return (T) str;
}else if (clazz = = Long.class | | clazz = = long.class) {
Return (T) long.valueof (str);
}else {
Return Json.tojavaobject (Json.parseobject (str), clazz);
}
}

private void Returntopool (Jedis Jedis) {
if (Jedis! = null) {
Jedis.close ();
}
}

}

5. Call Redisservice in the business layer, this post is simple, in the controller call, just do a test.
logic: First in Redis to determine if there is a key, there is read, otherwise read from the database, and then deposited into Redis.
Value to overwrite values after the change is performed
@Controller
@RequestMapping ("/demo")
public class Samplecontroller {

@Autowired
UserService UserService;

@Autowired
Redisservice Redisservice;


@RequestMapping ("/redis/get")
@ResponseBody
Public result<user> Redisget () {
User User = Redisservice.get (Userkey.getbyid, "" +1, User.class);
return result.success (user);
}

@RequestMapping ("/redis/set")
@ResponseBody
Public result<boolean> Redisset () {
User User = new user ();
User.setid (1);
User.setname ("1111");
Redisservice.set (Userkey.getbyid, "" +1, user);//userkey:id1
Return result.success (TRUE);
}


}








Springboot Integrated native Redis

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.